Models of any kind
Upload a model Kaimei has no reader of its own for as a graph of ONNX operators: what runs, what is only drawn, and how each step is shown.
Kaimei reads linear models, tree models and layer-by-layer networks with readers of its own. Any other model is uploaded as a general model graph: a structure of family: "graph" that writes the model down operator by operator, the way ONNX does, with ONNX's operators and arithmetic. The API runs it. That covers transformers and attention, LSTM, GRU and RNN layers, 1-D and transposed convolutions, upsampling, models with several inputs, and the scikit-learn estimators that exist only as conversions: naive Bayes, nearest neighbours, kernel SVMs, discriminant analysis, Gaussian processes, IsolationForest, and pipelines with PCA or PolynomialFeatures.
Nobody writes a graph by hand. client.models.upload converts the model on your machine, in memory, with the framework's own converter: torch.onnx.export for a torch.nn.Module, skl2onnx for scikit-learn, tf2onnx for Keras, TensorFlow SavedModels and .tflite files, jax2onnx for JAX and Flax (see more frameworks). It sends the structure and its tensors; the ONNX file is not uploaded and not stored. pip install "kaimei[onnx]" installs onnx and onnxscript, which PyTorch's newer exporter needs for Hugging Face language models and encoders; the other converters come with their frameworks. An ONNX model itself (a .onnx path, its bytes or an onnx.ModelProto) can be given in place of the estimator.
Arguments of client.models.upload for this route
"auto": Kaimei's own readers first, and ONNX when they refuse the model, can only draw it, or cannot call it (token ids, several inputs). "onnx" and "native" force a route. The structure's metadata.route says which was taken. An ONNX model is read as a graph whatever via says.An example input, as you would call the model with it, batch axis included; a tuple or dict of them for several inputs. Needed for token ids and for several inputs. Without it a table of feature_names, or an image of input_shape, is assumed. A graph's shapes are fixed by it: one row at a time, at the sizes of sample.
What an input is when its name and shape do not say (see what Kaimei works out): {"pixels": {"feature": "photo", "layout": "nchw"}}, {"ids": {"feature": "review", "part": "ids"}}, {"signal": {"feature": "call", "type": "audio", "sample_rate": 8000}}. It names inputs of the model as converted: X for scikit-learn, the input names of a Keras model's signature, the parameter names of a PyTorch forward (input_0, input_1, … for one that takes more values than it names). A name that is none of them is an error.
The output the prediction is read from, when the model has several.
The names of the classes, one for each value the output gives: a list, a tuple, a NumPy array or a pandas Index. Two or more make a model that ends in scores (logits) a classifier, and on a model with a sigmoid for each they make a multi-label one. A classifier that gives one value for a row takes two names, negative first. Labels of the wrong count are refused (param="labels").
For a segmentation model whose class axis Kaimei cannot tell from its graph, its labels or its shape: "chw" (class scores, then height and width), "hwc" (height, width, then class scores) or "indices" (a class number for each pixel).
For a segmentation model whose mask is one score for each pixel: where it is cut, in the model's own numbers (a pixel is the foreground at that score or more). Left out, Kaimei finds it from the model: 0.5 for a model that ends in a sigmoid, 0 for raw scores. A mask of several classes or of class numbers, another task and a value that is no number are refused with param="threshold". It is not a classifier's outputs.threshold.
Worked out from the model when left out (see what Kaimei works out). Besides the classifiers and regression: text_generation, sequence_to_sequence, generation or embedding (see generative models), and multilabel_classification, object_detection, segmentation or clustering (see labels, boxes, masks and groups).
Writes the converted ONNX model there, for the model's agent to run. It is not uploaded.
A diffusion model's sampler: a diffusers scheduler, whose own noise schedule goes into the structure, or the sampler's settings as a dict. A diffusers pipeline uploaded as it is brings its scheduler. See generate.
The check holds the library's answers, not the conversion's. A few rows go up with the structure with what PyTorch, scikit-learn or Keras gives for them, and the API runs them with its own engine before it runs the model. A conversion further than 1e-4 of its outputs' size from the library is marked approximate: drawn, not run. An ONNX file given directly is checked against ONNX Runtime, or ONNX's reference evaluator when ONNX Runtime is not installed. The rows are not stored. A scikit-learn model is computed in single precision when that gives the model's own numbers on rows from the range of its data, and in double precision otherwise (metadata.model_precision says which): give rows (X=) when a column holds large values that differ by little, such as a time in seconds.
A classifier is exact only when its class is the model's own. Besides its scores, the class Kaimei reports for a row (the highest probability; for a yes-or-no model, the positive class at its threshold) is compared with the model's own predict on every row of the check. Where they differ, the reading that agrees is used: a TunedThresholdClassifierCV or FixedThresholdClassifier is uploaded with its own decision threshold (outputs.threshold, and outputs.positive_label when its positive class is the first one), and a classifier whose predict goes by its scores where its probabilities tie (SGDClassifier(loss="modified_huber")) is read by its decision_function. When no reading agrees on every row, the model is uploaded drawn, not run, and its summary says on how many rows the class differs. Two kinds of model keep a note (metadata.predicted_class, and a warning) on an upload whose check rows all agree, because their rule is known to differ on other rows: an SVC or NuSVC with probability=True, whose predict goes by the margin, and one of more than two classes without break_ties=True, whose predict counts one-vs-one votes. An SVC with probabilities whose most probable class is not predict()'s on a row of the check is read by its decision_function instead. One with decision_function_shape="ovo" and more than two classes is refused: set it to "ovr".
A classifier without predict_proba (an SVC without probability=True, a OneVsOneClassifier) is read through its decision_function: the shares it reports are those scores made to add up to one, not calibrated probabilities. Keras goes through tf2onnx when it is installed: a Keras 3 model, recurrent layers included, through tf.function with the model's own input signature, an older one through tf2onnx.convert.from_keras. Without tf2onnx, or when its conversion cannot be used, a Keras model whose input is not a table or a picture is uploaded as Kaimei's own readers draw it (drawn, not run), with a warning.
# scikit-learn, through skl2onnx
client.models.upload(knn, name="Neighbours", feature_names=names,
X=X_train, y=y_train)
# a PyTorch LSTM: window is a (1, 24, 3) tensor
client.models.upload(forecaster, name="Demand", task="regression",
sample=window)
# an ONNX model itself
client.models.upload("model.onnx", name="From a file", feature_names=names)
# extract without uploading, and see which route was taken
extraction = kaimei.extract_structure(forecaster, sample=window)
print(extraction.spec["family"]) # graph
print(extraction.spec["metadata"]["route"])#What Kaimei works out
Most uploads need the model and an example input, nothing more. The client reads what the model is from the model itself, and the structure says what it found: task, the features and the labels. Any of them can still be given.
| The model is | When it has |
|---|---|
| A classifier | labels=, and ends in scores (the logits a PyTorch classifier ends in) |
| Yes or no | One output, through a sigmoid |
multilabel_classification | A sigmoid for each of several outputs, and labels= |
| A classifier or a regression | A Hugging Face …ForSequenceClassification, …ForImageClassification or …ForAudioClassification: the classes of id2label, several at once when problem_type says so |
text_generation | …ForCausalLM |
sequence_to_sequence | An encoder-decoder with a language-model head: …ForConditionalGeneration, MarianMTModel |
segmentation | …ForSemanticSegmentation |
object_detection | …ForObjectDetection |
embedding | A bare …Model with a pooled output |
clustering | A scikit-learn KMeans or Gaussian mixture |
generation | A diffusers pipeline, with its scheduler as the sampler |
Every input of the model is a feature of its own, by its name, type and shape:
- Whole numbers called
input_ids,idsortokens, or the only run of them the model looks up in an embedding table, are a text;attention_mask,token_type_idsand positions beside them are worked out from it. Any other whole number (a user, an item, a category) is anintegercolumn, from 0 to the size of the table it is looked up in, less one. - Floats. A single number is a column (a diffusion model's timestep), a run of up to 1,024 numbers a table of columns, and a longer one a tensor. A run of at least 256 called
input_values,waveform,audio,speechorsignal(and the like) is a recording, at 16,000 samples a second unlessinputs=gives asample_rate. Two axes are a series; three, with 1, 3 or 4 channels, a picture. - Hugging Face language models are exported with their cache turned off (
use_cache), so they convert as they are.
The example has to be one Kaimei can give. The client turns the example input into the features and back. When what comes back is not what the model was given (two inputs read from one feature, say), the upload is refused with param="inputs", naming them, and inputs= then says what each one is.
No quiet fallbacks. A model only a conversion can read, whose conversion fails, is refused with the reason rather than uploaded as a list of its layers. On every route, a sample, inputs, output, tokenizer, labels or max_length that does not fit the model is an error that names the argument, not a reason to try another route. inputs, tokenizer, mask_layout and an output other than a module's first are read only from a model converted to ONNX: with any of them via="auto" converts the model first, and via="native" refuses them. on_unsupported="error" refuses every reading Kaimei would only draw, on every route, and deletes again a model the API says it only draws. Anything else that answers with several numbers stays a regression and is drawn, and the upload's warning says which task= to pass.
# a PyTorch network ending in four sigmoids: with labels, a multi-label classifier
client.models.upload(tagger, name="Photo tags", sample=torch.randn(1, 6),
labels=["indoor", "people", "night", "text"])
# Hugging Face: the task and the classes come from the model's class and config
client.models.upload(segformer, name="Pet segmenter", sample=torch.rand(1, 3, 32, 32))
client.models.upload(detr, name="Pet finder", sample=torch.rand(1, 3, 64, 64))
# forward(self, waveform) on 16,000 samples: a recording
client.models.upload(spotter, name="Keyword spotter", sample=torch.randn(1, 16000),
labels=["yes", "no", "stop"])
extraction = kaimei.extract_structure(segformer, sample=torch.rand(1, 3, 32, 32))
print(extraction.spec["task"], extraction.spec["outputs"]["labels"])
# segmentation ['background', 'cat', 'dog']#More frameworks, and pipelines read exactly
- TensorFlow. A SavedModel (its directory) and a
.tflitefile are read throughtf2onnx, and the check holds what TensorFlow and its interpreter answer. - JAX. A function, a jitted function or a Flax NNX module goes through
jax2onnx;sample=gives the shapes (the model is converted for one row, whatever the number of rows the sample has), andframework="jax"says a plain function is one. - GGUF. A
.gguffile is opened by Hugging Facetransformers(withggufandaccelerateinstalled) and read as the PyTorch language model it is, with the tokenizer the file holds. Withoutsample=it reads 32 tokens, ormax_length=. A tokenizer Kaimei cannot split exactly (SentencePiece's) is uploaded aspieces: see tokenizers. - Bag-of-words text pipelines. A scikit-learn
Pipelineof aTfidfVectorizer(or aCountVectorizerand aTfidfTransformer) and a model is read exactly, its text split as scikit-learn splits it (awordtokenizer withpattern: "sklearn", its stop words and accents), so the feature takes text. A linear model or a naive Bayes is scored with its own coefficients; any other model after the counts, and steps between them (TruncatedSVD,SelectKBest, a scaler), is converted byskl2onnxand checked. Only scikit-learn's default token pattern and word analyzer are read, withstrip_accentsofNoneor"unicode"; a pipeline whose words Kaimei would find differently is refused, saying so. A bag of words counts every word, so a text is never cut to fit: the pipeline is read for 4,096 tokens, or for twice the longest text given (up to 32,768), or formax_length=, and its feature says"longer": "refuse", so a longer text is refused with an error (text and sequence models). A text in which the vectorizer finds no word is refused too, where scikit-learn answers it from the model's intercept. - Columns of categories. A pipeline that starts with a
ColumnTransformerof one-hot or ordinal encoders, scalers andSimpleImputers (each kind of column in aPipelineof its own or not), or with an encoder straight into the model, is read exactly too, in front of any model the ONNX route reads. A column an encoder reads becomes acategoricalfeature with the encoder's categories, and the graph is given each value's position among them; a missing value is sent asnulland the model is given what the imputer fills in. The columns are computed in double precision, as scikit-learn computes them, and a category the encoder never saw is refused, also when the encoder itself would let it pass.
Each is checked like any other conversion: the check holds what the framework itself answers, and a classifier pipeline is exact only when the class Kaimei reports is the pipeline's own predict() on every row of it.
client.models.upload("exported/", name="From TensorFlow", feature_names=names) # a SavedModel
client.models.upload("model.tflite", name="On device")
client.models.upload(nnx_module, name="From JAX", sample=jnp.ones((1, 5)),
feature_names=names, labels=["a", "b", "c"])
client.models.upload("tiny-llama.gguf", name="Small writer")
# scikit-learn pipelines, read exactly
words = Pipeline([("v", TfidfVectorizer()), ("m", LogisticRegression())]).fit(texts, y)
client.models.upload(words, name="Review words", X=texts, feature_names=["review"])
client.models.upload(churn, name="Churn with cities", X=frame, y=answer) # ColumnTransformer first#What runs
Operators are ONNX's, by ONNX's names, attributes and arithmetic, for the operator set versions the graph declares. Kaimei runs them itself, in the model's own number types, and each one is tested against ONNX's reference implementation and ONNX Runtime. Where those two disagree, Kaimei follows ONNX Runtime, since that is what a model's owner checks against.
- Every operator of ONNX's default domain and of its classical machine-learning domain (
ai.onnx.ml: linear models, SVMs, tree ensembles, scalers, encoders) runs, control flow included (If,Loop,Scan), except two:RegexFullMatchandImageDecoder. - What ONNX Runtime's tools write into models runs too: the quantized
QLinear*operators andQGemm,Gelu,FusedMatMul, the fused layer normalisations andCDist. Quantized models run in their integers, in both of the forms they are written in. Detectors run with their box operators,NonMaxSuppressionandRoiAlign. - Steps that draw at random (
RandomNormal,Bernoulliand the like) use their own seed, and seed 0 when they have none, so a model gives the same answer every time. The client gives each such step of a converted model a seed and records the model's answers with those seeds (metadata.seeded_steps), so the check holds the graph to the same draws. - Rows are scored in batches when running the graph shows that each row keeps its own values: three rows alone, then together. Every batch is then held to its own rows: one or two of them are scored again alone, and a graph caught giving a row different values in a batch is scored a row at a time from then on. A batch can cost a row or two more than it holds; it never returns another row's numbers.
- On the API's processors. The API runs a graph on its own CPUs. That is fine for small and medium models and slow for large ones: a large model is better run by its agent, on its own hardware.
For this release the route was run against the API on 33 models: scikit-learn estimators (naive Bayes, nearest neighbours, SVMs with RBF and polynomial kernels, discriminant analysis, a Gaussian process, an isolation forest, pipelines with PCA, polynomial features or an imputer), PyTorch LSTM, GRU and bidirectional models, a transformer text classifier, a small GPT, 1-D convolutions, upsampling, a model with two inputs, autoencoders and an embedding model, and three ONNX files. All of them ran, within 3e-5 of the library's own predictions on held-out rows.
{
"format": "kaimei.structure.v1",
"family": "graph",
"task": "binary_classification",
"framework": "pytorch",
"features": [
{"name": "review", "type": "text", "max_length": 16}
],
"tokenizers": {
"review": {
"type": "word",
"vocab": ["<pad>", "<unk>", "the", …],
"unk": "<unk>",
"pad": "<pad>"
}
},
"graph": {
"opsets": {"": 17},
"inputs": [
{
"name": "ids",
"dtype": "int64",
"shape": [1, 16],
"from": {"feature": "review", "part": "ids"}
}
],
"constants": {
"table": {"$tensor": "embed.weight"},
"w": [[0.1, -0.2]],
"b": [0.0, 0.0]
},
"nodes": [
{
"id": "embed",
"op": "Gather",
"inputs": ["table", "ids"],
"outputs": ["embedded"],
"path": "embed"
},
{
"id": "pool",
"op": "ReduceMean",
"inputs": ["embedded"],
"outputs": ["pooled"],
"attrs": {
"axes": [1],
"keepdims": 0
}
},
{
"id": "fc",
"op": "Gemm",
"inputs": ["pooled", "w", "b"],
"outputs": ["logits"],
"attrs": {"transB": 1},
"path": "head.fc"
}
],
"outputs": ["logits"],
"values": {
"embedded": {
"shape": [1, 16, 32],
"dtype": "float32"
}
}
},
"head": {"output": "logits", "link": "softmax"},
"outputs": {
"labels": ["negative", "positive"]
},
"check": {
"inputs": {
"review": [
[
2, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1
]
]
},
"outputs": [[0.31, 0.69]]
}
}#Drawn, not run
A model that cannot be run here still uploads. It is registered and drawn in full, every step with its attributes and shape, and the structure's summary and the client's warning say why it is not run. It can still be predicted, explained and looked into through a scoring endpoint or its agent.
| A graph is drawn, not run, when | What to do |
|---|---|
| One of its operators has no kernel. The upload names it. | Run the model where it is, with an agent or an endpoint. |
Some of its tensors were sent as shapes (weights="summary" or "pictures"). | The same: the weights are with you. |
Its check does not reproduce the library's answers, or the class Kaimei would report for a row of it is not the model's own (approximate). | The same: an agent runs the model itself. |
A value one of its inputs is always given was sent as its shape (weights="summary" with inputs={name: {"value": …}}). | The same. |
Its tensor sizes depend on the data (Unique, NonZero feeding what follows): a tensor may not come out larger than the shape it was declared with, and other rows soon make one that does. | An agent or an endpoint. |
| It is a regression that answers with several numbers. | Register it as what it is (generation, whose answer is a tensor, or multilabel_classification, object_detection, segmentation), or pick one output with output=. The upload's warning says which. |
| It is past what this server holds for one pass: 60,000 steps, bodies nested 4 deep, 1 GiB of values for a row or 1 GiB of tensors (what a request may spend). | Upload its weights as a summary and run it with an agent; see models of any size. |
A single matrix that is inverted, or whose determinant is taken, may have 2,048 rows. A malformed graph is refused at upload with 400 invalid_structure, never a server error.
#What a request may spend
The API runs every model on its own processors, alongside everyone else's requests. These limits keep one model from holding the server. Each answers with an error and leaves the server as it was.
| Limit | How much | Past it |
|---|---|---|
| One pass of a graph | 60 seconds | 422 run_time_exceeded |
| All the passes of one request together, counted from its first pass, whatever it asks for: a batch of predictions, an explanation's evaluations, a trace | 90 seconds | 422 request_time_exceeded |
| All the passes of one background analysis | 900 seconds | The analysis fails, saying so |
| What a pass holds for a row, and the tensors it reads | 1 GiB and 1 GiB | The model is drawn, not run (422 model_too_large_to_run when asked) |
The values a pass holds and does not show, steps inside If, Loop and Scan included | 256 MiB | 422 structure_too_large, before the value is made |
Values are counted at their real size: text by its characters, sequences and maps by what they hold, and what a Loop or Scan collects. An explanation by parts and a generation plan to fit times of their own, which are shorter: see explanations by parts and generate. A self-hosted API sets each of these (self-hosting).
At upload, the pass that finds the shapes a graph leaves out runs under the same limits. A graph whose constants are larger than a pass may hold, or whose inputs or shown tensors are, declares its shapes in graph.values (see the graph spec). Concurrent requests for one graph that is not loaded yet compile it once.
By plan. Every plan has every feature; the plans differ in their limits. Two of the limits are about what this page describes: how many models your own agent runs (1 on Free, 5 on Standard, 25 on Team, no limit on Enterprise; a model and its versions are one), and how many numbers one model graph keeps on Kaimei (25 million, 100 million, 500 million, no limit; a constant sent as a shape only is not kept and does not count). Past either the answer is 403 quota_exceeded and nothing is stored. GET /v1/billing lists them for each plan under capacities.
#How each step is shown
The dashboard and the structure document draw one node for each tensor a person is shown, grouped by the model's module path. Steps that carry no data are run and not drawn: those that only compute shapes (Shape, Size and what is made from them alone) and arithmetic on constants. A layer's own tensors (a convolution's kernel, a linear layer's weight, an embedding table, a recurrent layer's matrices) are its parameters, and small ones are shown as its arguments.
A shown shape says what a tensor is, whatever order the model keeps it in:
- Three sizes are always a feature map, height × width × channels, or attention weights, queries × keys × heads, which also say
role: "attention". A tensor is a map when a convolution, a pooling or a normalisation over channels makes it or reads it, and anything that only passes a map on keeps it one. - Two sizes are rows × columns. Every other tensor of three axes or more is shown as a table, its first axis down and the rest across: tokens × heads × sizes is tokens × the rest.
- Axes of one are left out, except that rows of one value each stay rows: a series of one channel is
[48, 1], and a recurrent layer's last state, kept behind two axes of one, is[24].
Each node's args carry the operator, its attributes, the shape shown, and the tensor as the model keeps it (tensor.shape, dtype, and perm when it is shown in another order).
{
"id": "blocks.0.Softmax",
"kind": "activation",
"op": "Softmax",
"label": "Softmax",
"detail": "over axis -1",
"units": 512,
"path": "blocks.0.Softmax",
"block": "blocks.0",
"inputs": ["blocks.0.Add"],
"args": {
"op": "Softmax",
"attrs": {"axis": -1},
"shape": [16, 16, 2],
"tensor": {
"shape": [1, 2, 16, 16],
"dtype": "float32",
"perm": [0, 2, 3, 1]
},
"role": "attention"
}
}#Models of any size
The limits above are on what this server holds and runs, not on what it can draw. A model too large for them is still registered, drawn in full and looked into:
- Its tensors are sent as shapes.
weights="summary"sends each tensor as{"$shape", "dtype", "stats"}: its shape, its number type and statistics worked out where the weights are. Nothing is held for such a tensor, so it is not counted against the limits on uploaded values (250 million a tensor, 2 billion a model), and a model of billions of parameters registers. Its structure is still every step; the shapes come from the graph's declaredvalues. - Pictures, when you ask for them.
weights="pictures"is a summary that also sends a small picture of each float tensor of 256 values or more: the tensor as a matrix, cut into whole blocks of rows and columns, at most 64 cells a side, each the strongest value of its block, at 8 bits. The dashboard draws it where the weights would be. It is never the default: a tensor of 64 by 64 values or fewer is all there in its picture. - Its values come from its agent. The real model, run where it lives, answers predictions and explanations and says what each step computed. See agents.
GET …/structure/parameters/{id}?side=N returns a tensor as a picture of at most N cells a side. For a tensor whose values are on the server, each cell stands for a block by its strongest value or the mean (pool), and rows and cols zoom into a window, down to one value a cell (source: "values"). For a tensor sent without its values it returns the picture its owner sent, with no window to zoom into (source: "summary"); such a parameter says pictured: true in the structure document.
model = client.models.upload(
net, name="Encoder", task="binary_classification", sample=ids, tokenizer=tokenizer,
weights="pictures", # shapes, statistics and a 64 × 64 sketch of each large tensor
inference={"type": "agent"}, # the weights stay here; the agent runs the model
save_onnx="encoder.onnx",
)
sketch = client.models.parameter_view(model.id, "encoder.layers.0.attn.q_proj.weight")
print(sketch.source) # summary: the picture sent with the upload
# a tensor the API holds: any window of it, as fine as one value a cell
zoom = client.models.parameter_view("review-sentiment-v1", "blocks.0.up.MatMul.weight",
side=4, rows=(0, 8), cols=(0, 8), pool="mean")
print(zoom.window, zoom.cell) # {'rows': [0, 8], 'cols': [0, 8]} {'rows': 2, 'cols': 2, 'pool': 'mean'}curl "https://api.kaimei.ai/v1/models/review-sentiment-v1/structure/parameters/blocks.0.up.MatMul.weight?side=8" \
-H "Authorization: Bearer $KAIMEI_API_KEY"