Skip to content

Commit e214e32

Browse files
Add inspect function to the python package (#306)
The `inspect` function has been added to the `encoderfile` package. The config classes have been annotated for python use via pyo3.
1 parent c199b3b commit e214e32

8 files changed

Lines changed: 143 additions & 10 deletions

File tree

encoderfile-py/src/builder.rs

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1+
use std::collections::HashMap;
12
use std::path::PathBuf;
23

3-
use encoderfile::builder::builder::EncoderfileBuilder;
4+
use encoderfile::builder::cli::inspect::inspect_encoderfile;
5+
use encoderfile::builder::{builder::EncoderfileBuilder, cli::inspect::InspectInfo};
6+
use encoderfile::common::Config;
7+
use encoderfile::common::ModelConfig;
48
use pyo3::{
59
exceptions::{PyIOError, PyRuntimeError},
610
prelude::*,
@@ -45,3 +49,82 @@ impl PyEncoderfileBuilder {
4549
Ok(())
4650
}
4751
}
52+
53+
#[pyclass(name = "InspectInfo", frozen)]
54+
pub struct PyInspectInfo(InspectInfo);
55+
56+
#[pymethods]
57+
impl PyInspectInfo {
58+
#[getter]
59+
fn get_model_config(&self) -> PyResult<PyModelConfig> {
60+
Ok(PyModelConfig(self.0.model_config.clone()))
61+
}
62+
#[getter]
63+
fn get_encoderfile_config(&self) -> PyResult<PyEncoderfileConfig> {
64+
Ok(PyEncoderfileConfig(self.0.encoderfile_config.clone()))
65+
}
66+
}
67+
68+
#[pyclass(name = "ModelConfig", frozen)]
69+
pub struct PyModelConfig(ModelConfig);
70+
71+
#[pymethods]
72+
impl PyModelConfig {
73+
#[getter]
74+
fn get_model_type(&self) -> String {
75+
self.0.model_type.clone()
76+
}
77+
78+
#[getter]
79+
fn get_num_labels(&self) -> Option<usize> {
80+
self.0.num_labels()
81+
}
82+
83+
#[getter]
84+
fn get_id2label(&self) -> Option<HashMap<u32, String>> {
85+
self.0.id2label.clone()
86+
}
87+
88+
#[getter]
89+
fn get_label2id(&self) -> Option<HashMap<String, u32>> {
90+
self.0.label2id.clone()
91+
}
92+
}
93+
94+
#[pyclass(name = "EncoderfileConfig", frozen)]
95+
pub struct PyEncoderfileConfig(Config);
96+
97+
#[pymethods]
98+
impl PyEncoderfileConfig {
99+
#[getter]
100+
fn get_name(&self) -> String {
101+
self.0.name.clone()
102+
}
103+
104+
#[getter]
105+
fn get_version(&self) -> String {
106+
self.0.version.clone()
107+
}
108+
109+
#[getter]
110+
fn get_model_type(&self) -> String {
111+
format!("{:?}", self.0.model_type)
112+
}
113+
114+
#[getter]
115+
fn get_transform(&self) -> Option<String> {
116+
self.0.transform.clone()
117+
}
118+
119+
#[getter]
120+
fn get_lua_libs(&self) -> Option<Vec<String>> {
121+
Some(self.0.lua_libs?.into())
122+
}
123+
}
124+
125+
#[pyfunction]
126+
pub fn inspect(_py: Python<'_>, path: &str) -> PyResult<PyInspectInfo> {
127+
let result = inspect_encoderfile(path)
128+
.map_err(|e| PyRuntimeError::new_err(format!("Failed to inspect encoderfile: {:?}", e)))?;
129+
Ok(PyInspectInfo(result))
130+
}

encoderfile-py/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,7 @@ mod builder;
77
mod encoderfile {
88
#[pymodule_export]
99
use super::builder::PyEncoderfileBuilder;
10+
11+
#[pymodule_export]
12+
use super::builder::inspect;
1013
}

encoderfile/src/builder/cli/inspect.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,26 @@ use crate::{
1414

1515
// inspect struct with info
1616

17-
#[derive(Debug, Serialize)]
17+
#[derive(Debug, Serialize, Clone)]
1818
pub struct InspectInfo {
1919
pub model_config: ModelConfig,
2020
pub encoderfile_config: Config,
2121
}
2222

23-
pub fn inspect_encoderfile(path_str: &String) -> Result<String> {
23+
pub fn inspect_encoderfile(path_str: &str) -> Result<InspectInfo> {
2424
let file = File::open(Path::new(&path_str))?;
2525
let mut file = BufReader::new(file);
2626
let mut loader = load_assets(&mut file)?;
2727

2828
let config = loader.encoderfile_config()?;
2929
let model_config = loader.model_config()?;
3030

31-
Ok(to_string_pretty(&InspectInfo {
31+
Ok(InspectInfo {
3232
model_config,
3333
encoderfile_config: config,
34-
})?)
34+
})
35+
}
36+
37+
pub fn inspect_encoderfile_pretty(path_str: &str) -> Result<String> {
38+
Ok(to_string_pretty(&inspect_encoderfile(path_str)?)?)
3539
}

encoderfile/src/builder/cli/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::path::PathBuf;
44
use clap_derive::{Args, Parser, Subcommand};
55

66
mod build;
7-
mod inspect;
7+
pub mod inspect;
88
mod runtime;
99

1010
#[cfg(feature = "dev-utils")]
@@ -70,7 +70,7 @@ impl Commands {
7070
Self::Runtime(r) => r.execute(global),
7171
Self::NewTransform { model_type } => super::transforms::new_transform(model_type),
7272
Self::Inspect { path } => {
73-
println!("{}", inspect::inspect_encoderfile(&path)?);
73+
println!("{}", inspect::inspect_encoderfile_pretty(&path)?);
7474
Ok(())
7575
}
7676
}

encoderfile/src/common/config.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use anyhow::{Result, bail};
33
use serde::{Deserialize, Serialize};
44
use tokenizers::{PaddingParams, TruncationParams};
55

6-
#[derive(Debug, Serialize, Deserialize)]
6+
#[derive(Debug, Serialize, Deserialize, Clone)]
77
pub struct Config {
88
pub name: String,
99
pub version: String,
@@ -57,6 +57,26 @@ impl TryFrom<Vec<String>> for LuaLibs {
5757
}
5858
}
5959

60+
impl From<LuaLibs> for Vec<String> {
61+
fn from(value: LuaLibs) -> Vec<String> {
62+
[
63+
("coroutine", value.coroutine),
64+
("table", value.table),
65+
("io", value.io),
66+
("os", value.os),
67+
("string", value.string),
68+
("utf8", value.utf8),
69+
("math", value.math),
70+
("package", value.package),
71+
("debug", value.debug),
72+
]
73+
.into_iter()
74+
.filter(|&(_k, v)| v)
75+
.map(|(k, _)| k.to_string())
76+
.collect()
77+
}
78+
}
79+
6080
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
6181
pub struct TokenizerConfig {
6282
pub padding: PaddingParams,

encoderfile/src/common/model_config.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use serde::{Deserialize, Serialize};
22
use std::collections::HashMap;
33

4-
#[derive(Debug, Serialize, Deserialize)]
4+
#[derive(Debug, Serialize, Deserialize, Clone)]
55
pub struct ModelConfig {
66
pub model_type: String,
77
pub num_labels: Option<usize>,

test_config.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ encoderfile:
22
name: my-model-2
33
path: models/token_classification
44
model_type: token_classification
5-
output_path: ./my-model-2.encoderfile
5+
output_path: ./test-model.encoderfile
66
transform: |
77
--- Applies a softmax across token classification logits.
88
--- Each token classification is normalized independently.

test_config_lua.yml

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
encoderfile:
2+
name: my-model-2-lua
3+
path: models/dummy_electra_token_classifier
4+
model_type: token_classification
5+
output_path: ./test-model-lua.encoderfile
6+
lua_libs:
7+
- table
8+
- math
9+
transform: |
10+
--- Applies a softmax across token classification logits.
11+
--- Each token classification is normalized independently.
12+
---
13+
--- Args:
14+
--- arr (Tensor): A tensor of shape [batch_size, n_tokens, n_labels].
15+
--- The softmax is applied along the third axis (n_labels).
16+
---
17+
--- Returns:
18+
--- Tensor: The input tensor with softmax-normalized embeddings.
19+
---@param arr Tensor
20+
---@return Tensor
21+
function Postprocess(arr)
22+
return arr:softmax(3)
23+
end

0 commit comments

Comments
 (0)