Skip to content

Commit 5b7c04e

Browse files
Session refactor and execution provider management (#390)
Co-authored-by: Raz Besaleli <besaleli@mozilla.ai>
1 parent 5156a18 commit 5b7c04e

15 files changed

Lines changed: 530 additions & 182 deletions

File tree

encoderfile-runtime/Cargo.toml

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@ version = "0.6.2"
44
edition = "2024"
55
publish = false
66

7+
[features]
8+
default = []
9+
coreml = ["encoderfile/coreml"]
10+
cuda = ["encoderfile/cuda"]
11+
bench = []
12+
dev-utils = []
13+
714
[dependencies]
815

916
[dependencies.encoderfile]
@@ -23,7 +30,3 @@ workspace = true
2330

2431
[dependencies.tokio]
2532
workspace = true
26-
27-
[features]
28-
bench = []
29-
dev-utils = []

encoderfile-runtime/src/main.rs

Lines changed: 8 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,22 @@
1-
use parking_lot::Mutex;
2-
use std::{
3-
fs::File,
4-
io::{BufReader, Read, Seek},
5-
sync::Arc,
6-
};
1+
use std::{fs::File, io::BufReader};
72

83
use anyhow::Result;
94
use clap::Parser;
10-
use encoderfile::{
11-
common::{
12-
ModelType,
13-
model_type::{Embedding, SentenceEmbedding, SequenceClassification, TokenClassification},
14-
},
15-
runtime::{EncoderfileLoader, EncoderfileState, load_assets},
16-
transport::cli::Cli,
17-
};
5+
use encoderfile::{runtime::load_assets, transport::cli::Cli};
186

197
#[tokio::main]
208
async fn main() -> Result<()> {
9+
// parse CLI
10+
let cli = Cli::parse();
11+
2112
// open current executable
2213
let path = std::env::current_exe()?;
2314
let file = File::open(path)?;
2415
let mut file = BufReader::new(file);
16+
2517
// load encoderfile
2618
let mut loader = load_assets(&mut file)?;
2719

28-
// entrypoint
29-
entrypoint(&mut loader).await
30-
}
31-
32-
macro_rules! run_cli {
33-
($model_type:ident, $cli:expr, $config:expr, $session:expr, $tokenizer:expr, $model_config:expr) => {{
34-
let state = Arc::new(EncoderfileState::<$model_type>::new(
35-
$config,
36-
$session,
37-
$tokenizer,
38-
$model_config,
39-
));
40-
$cli.command.execute(state).await
41-
}};
42-
}
43-
44-
async fn entrypoint<'a, R: Read + Seek>(loader: &mut EncoderfileLoader<'a, R>) -> Result<()> {
45-
let cli = Cli::parse();
46-
let session = Mutex::new(loader.session()?);
47-
let model_config = loader.model_config()?;
48-
let tokenizer = loader.tokenizer()?;
49-
let config = loader.encoderfile_config()?;
50-
51-
match loader.model_type() {
52-
ModelType::Embedding => run_cli!(Embedding, cli, config, session, tokenizer, model_config),
53-
ModelType::SequenceClassification => run_cli!(
54-
SequenceClassification,
55-
cli,
56-
config,
57-
session,
58-
tokenizer,
59-
model_config
60-
),
61-
ModelType::TokenClassification => run_cli!(
62-
TokenClassification,
63-
cli,
64-
config,
65-
session,
66-
tokenizer,
67-
model_config
68-
),
69-
ModelType::SentenceEmbedding => run_cli!(
70-
SentenceEmbedding,
71-
cli,
72-
config,
73-
session,
74-
tokenizer,
75-
model_config
76-
),
77-
}
20+
// execute
21+
cli.command.execute(&mut loader).await
7822
}

encoderfile/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@ transport = [
107107
dev-utils = ["transport"]
108108
cli = ["dep:console"]
109109
internal = []
110+
cuda = ["ort/cuda", "ort/tensorrt"]
111+
coreml = ["ort/coreml"]
110112

111113
[dev-dependencies]
112114
tempfile = "3.23.0"

encoderfile/proto/manifest.proto

Lines changed: 60 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -14,54 +14,51 @@ import "proto/metadata.proto";
1414
// This schema is NOT a general-purpose manifest and MUST NOT be extended
1515
// to support dynamic loading, headless execution, or runtime configuration.
1616
message EncoderfileManifest {
17-
// ------------------------------------------------------------------
18-
// 1–49: General model metadata
19-
// ------------------------------------------------------------------
20-
21-
// Logical model type (e.g. embedding, sentence-embedding, classification).
22-
// Used to validate compatibility with the runtime binary.
23-
encoderfile.metadata.ModelType model_type = 1;
24-
25-
// User-declared model name.
26-
// This value is informational and has no behavioral impact.
27-
string name = 2;
28-
29-
// User-declared model version.
30-
// This value is informational and has no behavioral impact.
31-
string version = 3;
32-
33-
// Backend.
34-
Backend backend = 4;
35-
36-
// ------------------------------------------------------------------
37-
// 50–99: Transforms and preprocessing
38-
// ------------------------------------------------------------------
39-
40-
// ------------------------------------------------------------------
41-
// 100–999: Embedded artifacts
42-
// ------------------------------------------------------------------
43-
// Artifacts are referenced via explicit fields, not a generic table.
44-
// Each artifact reserves its own numeric range for future expansion.
45-
// Any protobuf field ≥100 that participates in layout or runtime loading
46-
// MUST have value-independent encoded size.
47-
48-
// Model weights blob.
49-
optional Artifact weights = 100;
50-
51-
// Optional transform blob applied during model initialization.
52-
// If present, the runtime must support the declared TransformType.
53-
optional Artifact transform = 110;
54-
55-
// Model configuration (e.g. architecture, hyperparameters).
56-
optional Artifact model_config = 120;
57-
58-
// Tokenizer data (vocab, merges, config).
59-
// Serialized runtime::tokenizer::TokenizerService
60-
optional Artifact tokenizer = 130;
17+
// ------------------------------------------------------------------
18+
// 1–49: General model metadata
19+
// ------------------------------------------------------------------
20+
21+
// Logical model type (e.g. embedding, sentence-embedding, classification).
22+
// Used to validate compatibility with the runtime binary.
23+
encoderfile.metadata.ModelType model_type = 1;
24+
25+
// User-declared model name.
26+
// This value is informational and has no behavioral impact.
27+
string name = 2;
28+
29+
// User-declared model version.
30+
// This value is informational and has no behavioral impact.
31+
string version = 3;
32+
33+
// ------------------------------------------------------------------
34+
// 50–99: Transforms and preprocessing
35+
// ------------------------------------------------------------------
36+
37+
// ------------------------------------------------------------------
38+
// 100–999: Embedded artifacts
39+
// ------------------------------------------------------------------
40+
// Artifacts are referenced via explicit fields, not a generic table.
41+
// Each artifact reserves its own numeric range for future expansion.
42+
// Any protobuf field ≥100 that participates in layout or runtime loading
43+
// MUST have value-independent encoded size.
44+
45+
// Model weights blob.
46+
optional Artifact weights = 100;
47+
48+
// Optional transform blob applied during model initialization.
49+
// If present, the runtime must support the declared TransformType.
50+
optional Artifact transform = 110;
51+
52+
// Model configuration (e.g. architecture, hyperparameters).
53+
optional Artifact model_config = 120;
54+
55+
// Tokenizer data (vocab, merges, config).
56+
// Serialized runtime::tokenizer::TokenizerService
57+
optional Artifact tokenizer = 130;
6158
}
6259

6360
message LuaLibs {
64-
repeated string libs = 1;
61+
repeated string libs = 1;
6562
}
6663

6764
// Transform describes embedded preprocessing/postprocessing steps applied to inputs
@@ -70,52 +67,37 @@ message LuaLibs {
7067
// Transforms are embedded source code and executed by the runtime.
7168
// Only explicitly supported TransformTypes are allowed.
7269
message Transform {
73-
// Declares the execution environment for the transform.
74-
TransformType transform_type = 1;
70+
// Declares the execution environment for the transform.
71+
TransformType transform_type = 1;
7572

76-
// Transform source code.
77-
// Interpretation is defined by the TransformType.
78-
string transform = 2;
73+
// Transform source code.
74+
// Interpretation is defined by the TransformType.
75+
string transform = 2;
7976

80-
optional LuaLibs lua_libs = 3;
77+
optional LuaLibs lua_libs = 3;
8178
}
8279

8380
// Artifact describes a contiguous byte range within the embedded payload.
8481
//
8582
// Byte offsets are relative to manifest offset found in footer, not the start of the binary.
8683
message Artifact {
87-
// Byte offset relative to manifest offset found in footer
88-
fixed64 offset = 1;
84+
// Byte offset relative to manifest offset found in footer
85+
fixed64 offset = 1;
8986

90-
// Length of the artifact in bytes.
91-
fixed64 length = 2;
87+
// Length of the artifact in bytes.
88+
fixed64 length = 2;
9289

93-
// SHA-256 checksum of the artifact contents, hex-encoded.
94-
// Used for integrity verification at runtime.
95-
// MUST always be 32 bytes.
96-
bytes sha256 = 3;
90+
// SHA-256 checksum of the artifact contents, hex-encoded.
91+
// Used for integrity verification at runtime.
92+
// MUST always be 32 bytes.
93+
bytes sha256 = 3;
9794
}
9895

9996
// Supported transform types.
10097
enum TransformType {
101-
// Unspecified transform type. This should not be used.
102-
TRANSFORM_TYPE_UNSPECIFIED = 0;
98+
// Unspecified transform type. This should not be used.
99+
TRANSFORM_TYPE_UNSPECIFIED = 0;
103100

104-
// Lua source executed by the runtime.
105-
LUA = 1;
106-
}
107-
108-
// Execution backend required by the embedded runtime binary.
109-
//
110-
// This enum is informational here; backend compatibility is enforced
111-
// by the runtime binary itself, not by the payload.
112-
enum Backend {
113-
// CPU-only execution (no hardware acceleration).
114-
CPU = 0;
115-
116-
// NVIDIA CUDA backend.
117-
CUDA = 1;
118-
119-
// Apple Metal backend.
120-
METAL = 2;
101+
// Lua source executed by the runtime.
102+
LUA = 1;
121103
}

encoderfile/src/builder/builder.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ use crate::{
1616
assets::{AssetKind, AssetPlan, AssetSource, PlannedAsset},
1717
codec::EncoderfileCodec,
1818
},
19-
generated::manifest::Backend,
2019
};
2120
use anyhow::{Context, Result};
2221
use serde::{Deserialize, Serialize};
@@ -129,7 +128,6 @@ impl EncoderfileBuilder {
129128
self.config.encoderfile.name.clone(),
130129
self.config.encoderfile.version.clone(),
131130
self.config.encoderfile.model_type.clone(),
132-
Backend::Cpu,
133131
&asset_plan,
134132
&mut out,
135133
)?;

encoderfile/src/builder/model.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
use crate::format::assets::{AssetKind, AssetSource, PlannedAsset};
1+
use crate::{
2+
format::assets::{AssetKind, AssetSource, PlannedAsset},
3+
runtime::ORTSessionBuilder,
4+
};
25
use anyhow::{Result, bail};
36
use ort::{
47
session::{Output, Session},
@@ -12,7 +15,7 @@ pub trait ModelTypeExt {
1215

1316
impl ModelTypeExt for crate::common::ModelType {
1417
fn validate_model<'a>(&self, path: &'a Path) -> Result<PlannedAsset<'a>> {
15-
let model = load_model(path)?;
18+
let model = ORTSessionBuilder::default().from_file(path)?;
1619

1720
match self {
1821
Self::Embedding => validate_embedding_model(model),
@@ -74,7 +77,3 @@ fn get_outp_dim<'a>(outputs: &'a [Output], outp_name: &str) -> Result<&'a Shape>
7477
.tensor_shape()
7578
.ok_or(anyhow::anyhow!("Model must return tensor"))
7679
}
77-
78-
fn load_model(file: &Path) -> Result<Session> {
79-
Ok(Session::builder()?.commit_from_file(file)?)
80-
}

encoderfile/src/dev_utils/mod.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::{
33
Config, ModelConfig, TokenizerConfig,
44
model_type::{self, ModelTypeSpec},
55
},
6-
runtime::{AppState, EncoderfileState},
6+
runtime::{AppState, EncoderfileState, ORTSessionBuilder},
77
};
88
use ort::session::Session;
99
use parking_lot::Mutex;
@@ -62,12 +62,10 @@ fn get_tokenizer(dir: &str) -> crate::runtime::TokenizerService {
6262
}
6363

6464
fn get_model(dir: &str) -> Mutex<Session> {
65-
Mutex::new(
66-
ort::session::Session::builder()
67-
.expect("Failed to load session")
68-
.commit_from_file(format!("{}/{}", dir, "model.onnx"))
69-
.expect("Failed to load model"),
70-
)
65+
ORTSessionBuilder::default()
66+
.from_file(format!("{}/{}", dir, "model.onnx"))
67+
.expect("Failed to load model")
68+
.into()
7169
}
7270

7371
fn get_tokenizer_from_string(s: &str) -> crate::runtime::TokenizerService {

encoderfile/src/format/codec/decoder.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ mod tests {
4949
use crate::{
5050
common::model_type::ModelType,
5151
format::assets::{AssetKind, AssetPlan, AssetSource, PlannedAsset},
52-
generated::manifest::Backend,
5352
};
5453
use std::{
5554
borrow::Cow,
@@ -81,7 +80,6 @@ mod tests {
8180
"test-model".to_string(),
8281
"0.1.0".to_string(),
8382
ModelType::Embedding,
84-
Backend::Cpu,
8583
&plan,
8684
&mut buf,
8785
)
@@ -113,7 +111,6 @@ mod tests {
113111
"offset-test".to_string(),
114112
"1.0.0".to_string(),
115113
ModelType::Embedding,
116-
Backend::Cpu,
117114
&plan,
118115
&mut buf,
119116
)

0 commit comments

Comments
 (0)