Skip to content

Commit 0764004

Browse files
authored
docs: Python stub docstrings (#345)
1 parent 20c58f6 commit 0764004

1 file changed

Lines changed: 253 additions & 6 deletions

File tree

encoderfile-py/python/encoderfile/_core.pyi

Lines changed: 253 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,83 @@ from .enums import ModelType
33

44
@final
55
class TargetSpec:
6+
"""
7+
Represents a compilation target platform for building encoderfile binaries.
8+
9+
Attributes:
10+
arch: CPU architecture (e.g., ``"aarch64"``, ``"x86_64"``).
11+
os: Operating system (e.g., ``"apple"``, ``"unknown-linux"``).
12+
abi: ABI/environment suffix (e.g., ``"darwin"``, ``"gnu"``).
13+
"""
14+
615
arch: str
716
os: str
817
abi: str
9-
def __new__(cls, spec: str): ...
18+
def __new__(cls, spec: str):
19+
"""
20+
Parse a target triple string into a ``TargetSpec``.
21+
22+
Args:
23+
spec: A Rust-style target triple such as ``"aarch64-apple-darwin"``
24+
or ``"x86_64-unknown-linux-gnu"``. Equivalent to Cargo's
25+
``--target`` flag.
26+
"""
27+
...
1028

1129
@final
1230
class EncoderfileBuilder:
31+
"""
32+
Builds a self-contained encoderfile binary from an ONNX model.
33+
34+
The builder validates model files, embeds ONNX weights, tokenizer
35+
configuration, and model metadata into a pre-built base binary, then
36+
writes the result to the configured output path.
37+
38+
Typical usage::
39+
40+
builder = EncoderfileBuilder(
41+
name="sentiment-analyzer",
42+
model_type=ModelType.SequenceClassification,
43+
path="./models/distilbert-sst2",
44+
output_path="./sentiment-analyzer.encoderfile",
45+
)
46+
builder.build()
47+
48+
Alternatively, load configuration from a YAML file::
49+
50+
builder = EncoderfileBuilder.from_config("sentiment-config.yml")
51+
builder.build()
52+
"""
53+
1354
@staticmethod
1455
def from_config(
1556
config_path: str,
16-
) -> "EncoderfileBuilder": ...
57+
) -> "EncoderfileBuilder":
58+
"""
59+
Create an ``EncoderfileBuilder`` from a YAML configuration file.
60+
61+
The YAML file must contain an ``encoderfile`` top-level key whose
62+
value matches the ``EncoderfileConfig`` schema. Example::
63+
64+
encoderfile:
65+
name: sentiment-analyzer
66+
version: "1.0.0"
67+
path: ./models/distilbert-sst2
68+
model_type: sequence_classification
69+
output_path: ./build/sentiment-analyzer.encoderfile
70+
71+
Args:
72+
config_path: Path to the YAML build configuration file.
73+
74+
Returns:
75+
A configured ``EncoderfileBuilder`` instance.
76+
77+
Raises:
78+
ValueError: If the configuration file is missing required fields
79+
or contains invalid values.
80+
FileNotFoundError: If ``config_path`` does not exist.
81+
"""
82+
...
1783
def __new__(
1884
cls,
1985
*,
@@ -29,26 +95,135 @@ class EncoderfileBuilder:
2995
tokenizer: Optional[TokenizerBuildConfig] = None,
3096
validate_transform: bool = True,
3197
target: Optional[str | TargetSpec] = None,
32-
) -> "EncoderfileBuilder": ...
98+
) -> "EncoderfileBuilder":
99+
"""
100+
Create an ``EncoderfileBuilder`` with explicit configuration.
101+
102+
Args:
103+
name: Model identifier used in API responses and as the default
104+
output filename when ``output_path`` is not set.
105+
version: Model version string. Defaults to ``"0.1.0"``.
106+
model_type: Architecture of the model. Determines how inference
107+
outputs are structured (embeddings, sequence labels, or token
108+
labels).
109+
path: Path to a directory containing ``model.onnx``,
110+
``tokenizer.json``, and ``config.json``, or an explicit
111+
mapping of individual file paths.
112+
output_path: Destination path for the compiled binary. Defaults
113+
to ``./<name>.encoderfile`` in the current directory.
114+
cache_dir: Directory used for caching intermediate build
115+
artifacts. Defaults to the system cache directory.
116+
base_binary_path: Path to a local pre-built base binary. When
117+
provided, skips downloading the base binary from the network.
118+
transform: Lua post-processing script applied to model logits
119+
before returning results. May be an inline Lua string or a
120+
file path. Example::
121+
122+
"function Postprocess(logits) return logits:lp_normalize(2.0, 2.0) end"
123+
124+
lua_libs: Additional Lua library paths made available to the
125+
transform script at runtime.
126+
tokenizer: Tokenizer padding and truncation settings. Any values provided here will
127+
override any settings found in `tokenizer_config.json` or `tokenizer.json`.
128+
When ``None``, the tokenizer uses its default configuration.
129+
validate_transform: Whether to perform a dry-run validation of
130+
the transform script before building. Defaults to ``True``.
131+
target: Target platform triple for cross-compilation, supplied
132+
either as a ``"<arch>-<os>-<abi>"`` string or a
133+
``TargetSpec`` instance. Defaults to the host machine's
134+
architecture.
135+
136+
Returns:
137+
A configured ``EncoderfileBuilder`` instance ready to call
138+
:meth:`build`.
139+
"""
140+
...
141+
33142
def build(
34143
self,
35144
workdir: Optional[str] = None,
36145
version: Optional[str] = None,
37146
no_download: bool = False,
38-
): ...
147+
):
148+
"""
149+
Compile and write the encoderfile binary.
150+
151+
Performs the following steps:
152+
153+
1. Validates model files (``model.onnx``, ``tokenizer.json``,
154+
``config.json``).
155+
2. Validates the ONNX model structure and compatibility.
156+
3. Optionally validates the Lua transform with a dry run.
157+
4. Embeds all assets into the base binary.
158+
5. Writes the finished binary to ``output_path``.
159+
160+
Args:
161+
workdir: Temporary working directory for intermediate build
162+
files. Defaults to a system temp directory.
163+
version: Override the encoderfile runtime version to embed.
164+
Takes precedence over the version set on the builder.
165+
no_download: When ``True``, disables downloading the base
166+
binary from the network. A local base binary must be
167+
available via ``base_binary_path`` or the cache.
168+
169+
Raises:
170+
FileNotFoundError: If required model files are missing.
171+
ValueError: If the ONNX model structure is incompatible or
172+
the transform script fails validation.
173+
RuntimeError: If the binary cannot be written to
174+
``output_path``.
175+
"""
176+
...
39177

40178
@final
41179
class BatchLongest:
180+
"""
181+
Pad all sequences in a batch to the length of the longest sequence.
182+
183+
Use this as the ``pad_strategy`` on :class:`TokenizerBuildConfig` when
184+
you want dynamic, batch-relative padding rather than a fixed sequence
185+
length.
186+
"""
187+
42188
pass
43189

44190
@final
45191
class Fixed:
192+
"""
193+
Pad all sequences to a fixed sequence length.
194+
195+
Attributes:
196+
n: The fixed number of tokens every sequence will be padded or
197+
truncated to.
198+
"""
199+
46200
n: int
47201

48202
def __new__(cls, *, n: int) -> "Fixed": ...
49203

50204
@final
51205
class TokenizerBuildConfig:
206+
"""
207+
Tokenizer padding and truncation settings embedded at build time.
208+
209+
These settings are baked into the encoderfile binary and applied
210+
consistently at inference time without requiring runtime configuration.
211+
212+
Attributes:
213+
pad_strategy: How sequences are padded. ``BatchLongest`` pads to
214+
the longest sequence in each batch; ``Fixed(n=N)`` pads every
215+
sequence to exactly ``N`` tokens. ``None`` uses the
216+
tokenizer's default padding behaviour.
217+
truncation_side: Which side to truncate from when a sequence
218+
exceeds ``max_length``. Typically ``"left"`` or ``"right"``.
219+
truncation_strategy: Strategy used when truncating sequences that
220+
exceed ``max_length`` (e.g. ``"longest_first"``).
221+
max_length: Maximum number of tokens per sequence. Sequences
222+
longer than this value are truncated.
223+
stride: Number of overlapping tokens between consecutive chunks
224+
when a sequence is split due to ``max_length``.
225+
"""
226+
52227
pad_strategy: Optional[BatchLongest | Fixed]
53228
truncation_side: Optional[str]
54229
truncation_strategy: Optional[str]
@@ -63,17 +238,60 @@ class TokenizerBuildConfig:
63238
truncation_strategy: Optional[str] = None,
64239
max_length: Optional[int] = None,
65240
stride: Optional[int] = None,
66-
) -> "TokenizerBuildConfig": ...
241+
) -> "TokenizerBuildConfig":
242+
"""
243+
Args:
244+
pad_strategy: Padding strategy. Pass ``BatchLongest()`` for
245+
dynamic batch padding or ``Fixed(n=512)`` for a fixed
246+
sequence length.
247+
truncation_side: Side from which to truncate long sequences.
248+
truncation_strategy: Algorithm used to select which tokens to
249+
remove when truncating.
250+
max_length: Hard cap on sequence length in tokens.
251+
stride: Token overlap between sequence chunks produced by
252+
sliding-window truncation.
253+
"""
254+
...
67255

68256
@final
69257
class ModelConfig:
258+
"""
259+
Model architecture metadata extracted from the embedded ``config.json``.
260+
261+
Attributes:
262+
model_type: Architecture identifier as it appears in the HuggingFace
263+
config (e.g. ``"bert"``, ``"distilbert"``).
264+
num_labels: Number of output labels for classification models.
265+
``None`` for embedding models.
266+
id2label: Mapping from integer label index to label string
267+
(e.g. ``{0: "NEGATIVE", 1: "POSITIVE"}``). ``None`` when not
268+
present in the model config.
269+
label2id: Reverse mapping from label string to integer index.
270+
``None`` when not present in the model config.
271+
"""
272+
70273
model_type: str
71274
num_labels: Optional[int]
72275
id2label: Optional[dict[int, str]]
73276
label2id: Optional[dict[str, int]]
74277

75278
@final
76279
class EncoderfileConfig:
280+
"""
281+
Encoderfile-specific metadata embedded in the binary at build time.
282+
283+
Attributes:
284+
name: Model identifier as specified during the build.
285+
version: Model version string (e.g. ``"1.0.0"``).
286+
model_type: Encoderfile model type (``"embedding"``,
287+
``"sequence_classification"``, ``"token_classification"``, or
288+
``"sentence_embedding"``).
289+
transform: Inline Lua post-processing script, or ``None`` if no
290+
transform was embedded.
291+
lua_libs: Additional Lua library paths available to the transform,
292+
or ``None`` if none were specified.
293+
"""
294+
77295
name: str
78296
version: str
79297
model_type: str
@@ -82,7 +300,36 @@ class EncoderfileConfig:
82300

83301
@final
84302
class InspectInfo:
303+
"""
304+
Full introspection data returned by :func:`inspect`.
305+
306+
Attributes:
307+
model_config: Architecture metadata from the embedded
308+
``config.json``.
309+
encoderfile_config: Build-time metadata embedded by the
310+
``EncoderfileBuilder``.
311+
"""
312+
85313
model_config: ModelConfig
86314
encoderfile_config: EncoderfileConfig
87315

88-
def inspect(path: str) -> InspectInfo: ...
316+
def inspect(path: str) -> InspectInfo:
317+
"""
318+
Inspect an encoderfile binary without running inference.
319+
320+
Reads the metadata embedded in the binary at build time and returns it
321+
as an :class:`InspectInfo` object. Useful for verifying model type,
322+
version, and label mappings before deployment.
323+
324+
Args:
325+
path: Filesystem path to a compiled ``.encoderfile`` binary.
326+
327+
Returns:
328+
An :class:`InspectInfo` containing :class:`ModelConfig` and
329+
:class:`EncoderfileConfig` extracted from the binary.
330+
331+
Raises:
332+
FileNotFoundError: If no file exists at ``path``.
333+
ValueError: If the file is not a valid encoderfile binary.
334+
"""
335+
...

0 commit comments

Comments
 (0)