Text and sequence models

Text and sequence models

Models that read text, token ids, series, recordings or tensors: the feature types, the model's own tokenizer, and explanations by token, stretch or piece.

Five feature types sit beside columns and pictures. Each is many values at once, and each is explained by its parts.

typeDeclaresA value is
textmax_length: the token positions the model reads, 1 to 32,768; longer: "cut" (the default) or "refuse"A string, split by the model's tokenizer, or a list of token ids
tokensmax_length, and vocab_size when known; longer as for textA list of token ids
sequenceshape: [steps, channels]That many numbers, nested or flat
tensorshapeThat many numbers, nested or flat
audiosamples, and sample_rate (16,000 when left out)A recording: numbers, packed float32, or a WAV file as a data URL

A sequence or tensor feature has 1 to 6 axes and at most 8,000,000 values. A list of ids longer than max_length, or an id past the vocabulary, is 400 invalid_input. Aliases: series, timeseries and time_series are sequence; token_ids is tokens; array, vector, embedding and latent are tensor; sound and waveform are audio.

A text longer than the model reads. A language model's text longer than its max_length is 400 invalid_input, naming the limit, on predictions, explanations, generation and traces: cutting it would make the model continue another text. Any other model's text is cut as Hugging Face cuts it, keeping the special tokens around it, and the answer says so in output.input_truncated: {feature: {tokens, max_length}}. That is right for a model that reads the start of a text. A model whose answer depends on every token (a bag of words counts them all) says "longer": "refuse" on its feature: a text of more tokens than max_length is then 400 invalid_input, saying how many tokens it has and how many the model reads, on predictions, explanations, traces, activations and generation, and so is a text of more than 200,000 characters. A reference row that is too long is left out and counted in rejected. Any other value of longer is 400 invalid_feature_schema. The Python client sets it for the scikit-learn bag-of-words pipelines it reads.

Who runs the model decides what it is sent. Kaimei's own engine and a model's agent are given the token ids. A scoring endpoint is sent text for a text feature, written back from the ids by the registered tokenizer, and ids for a tokens feature: an endpoint that must see exactly the ids Kaimei worked with declares the feature as tokens.

The sample's length is the most tokens the model is ever given, because a converted graph's shapes are fixed. Give a sample as long as the texts you will send, or pass max_length= and the sample is filled up to it with the padding token. For a language model the prompt and what it writes share that length.

The client uploads reference rows (X=) for tables and pictures. For a model that reads text, a series, a recording or a tensor it leaves them out, with a warning: such a model needs none, because its explanations compare the input with itself. Its analyses run behavior and performance, which read only the model's answers; the others rank positions, not inputs, and are 422 method_not_applicable.

ids = tokenizer("an example", padding="max_length", max_length=128, return_tensors="pt")["input_ids"]
model = client.models.upload(
    classifier, name="Reviews", task="binary_classification",
    sample=ids, tokenizer=tokenizer,              # the token input becomes a text feature
    feature_names=["review"], labels=["negative", "positive"],
)
client.models.predict(model.id, input={"review": "the film was wonderful"})

# a series: 48 hours of load, one channel
client.models.predict("load-forecast-lstm-v1", input={"load": last_48_hours})
200 OKPOST …/review-sentiment-v1/predict
{
  "object": "prediction",
  "id": "pred_5aaf75b3ab7205d2435b",
  "model_id": "mdl_35636a1ada02058bf5fd",
  "input": {"review": "the film was really wonderful."},
  "output": {
    "label": "positive",
    "class_index": 1,
    "probability": 0.99994,
    "probabilities": {"negative": 6e-05, "positive": 0.99994},
    "target_label": "positive",
    "target_index": 1,
    "value": 0.99994,
    "name": "prediction"
  },
  "latency_ms": 1.81,
  "source": "kaimei"
}
outputa 50-token review sent to a model that reads 16
{
  "label": "positive",
  "class_index": 1,
  "probability": 0.999953,
  …: …,
  "input_truncated": {
    "review": {"tokens": 50, "max_length": 16}
  }
}

#Tokenizers

A tokenizer is part of the model. It is kept with the structure under tokenizers, by feature name, not on the feature, so a 50,000-token vocabulary is not carried by every model listing. A tokenizer file is never uploaded: the client writes the tokenizer down as JSON.

typeWhat it isKaimei splits text
charOne token per character.Yes
wordWords and punctuation, or scikit-learn's words (pattern: "sklearn").Yes
wordpieceBERT's.Yes
bpeByte-pair encoding: GPT-2's byte-level form, or plain with end_of_word.Yes
piecesA vocabulary alone, in id order, with space (what it writes for the space before a word, ▁ in SentencePiece's) or byte_level.No: its agent does, or the model takes token ids

Keys: vocab (a list, or tokens to ids), merges, lowercase, strip_accents, unk, pad, mask, eos, prefix and suffix (special tokens added around a text), added_tokens (each with piece: false when the tokenizer's own vocabulary does not hold it, so that no word is split into it), continuation, add_prefix_space and max_word_chars (WordPiece's max_input_chars_per_word), and for a byte-pair encoding Hugging Face's fuse_unk, byte_fallback and ignore_merges; a word tokenizer also takes pattern (words, the default, or sklearn: two or more word characters, as scikit-learn's vectorizers split text) and stop_words, and only those named patterns, since a pattern sent by a caller could be written to run without end. Special and added tokens written in a text ([MASK], <mask>, <|endoftext|>, tokens added with add_tokens) are matched as tokens through added_tokens, as Hugging Face matches them; byte-level BPE splits punctuation, and uncased WordPiece lowercases, the way Hugging Face does. Words of any length are split as Hugging Face splits them: byte-pair merges are made one at a time, lowest rank and leftmost first. A vocabulary has at most 400,000 tokens of up to 256 characters, and a byte-pair encoding at most 400,000 merges; every piece a merge joins, and the piece it makes, has to be a token of the vocabulary, or the tokenizer is refused, naming the piece. A tokenizer reads the first 200,000 characters of a text.

The client sends a tokenizer only once it is checked. tokenizer= takes a Kaimei description, a Hugging Face WordPiece tokenizer as BERT uses it, or a byte-level BPE tokenizer as GPT-2 and RoBERTa use it. A Hugging Face tokenizer is translated and compared with the original on the sample texts of kaimei.text.SAMPLE_TEXTS (odd spacing, punctuation, accents, other scripts, emoji, special and added tokens written in the text, and runs of hundreds of bytes with no break), and every text has to give exactly the same ids. The tokenizers of bert-base-uncased, bert-base-cased, distilbert-base-uncased, gpt2 and roberta-base pass. kaimei.text.tokenizer_spec(tokenizer, samples=[...]) runs the same comparison with texts of your own added, and its result can be passed as tokenizer=.

Any other tokenizer (SentencePiece, tiktoken, one of your own), and one that fails the comparison, is uploaded as pieces, with a warning. Kaimei then names every token and turns ids back into text, so explanations read as pieces of words, but it does not split text: encodes is false, and text is refused with tokenizer_not_found. Send the model token ids, or run its agent with the tokenizer: the agent splits every text first, and text then works everywhere. The model's profile says which: text.{feature}.split_by is server, agent or none.

POST /v1/models/{model}/tokenize lists exactly the tokens the model reads for a text, cut as a prediction cuts it, or names the tokens behind ids. It is a read: viewers can call it, and so can an organization whose plan has paused it. A text may have 20,000 characters (400 text_too_long), and calls with text are limited to 1,200 an hour on Free, more on paid plans.

tokens = client.models.tokenize("review-sentiment-v1", text="The film was really wonderful.")
print([t["token"] for t in tokens.tokens], tokens.truncated)
# ['the', 'film', 'was', 'really', 'wonderful', '.'] False

client.models.tokenize("review-sentiment-v1", ids=[2, 3, 4])   # names: acting, admired, and
curl https://api.kaimei.ai/v1/models/review-sentiment-v1/tokenize \
  -H "Authorization: Bearer $KAIMEI_API_KEY" -H "Content-Type: application/json" \
  -d '{"text": "The film was really wonderful."}'
200 OKResponse
{
  "object": "model.tokens",
  "model_id": "mdl_35636a1ada02058bf5fd",
  "feature": "review",
  "tokens": [
    {"token_id": 54, "token": "the"},
    {"token_id": 20, "token": "film"},
    {"token_id": 58, "token": "was"},
    {"token_id": 43, "token": "really"},
    {"token_id": 60, "token": "wonderful"},
    {"token_id": 61, "token": "."}
  ],
  "count": 6,
  "max_length": 16,
  "truncated": false,
  "tokenizer": {
    "type": "word",
    "vocab_size": 62,
    "encodes": true,
    "lowercase": true,
    "pad_id": 0,
    "unk_id": 1,
    "mask_id": null,
    "prefix": [],
    "suffix": []
  }
}

#Explanations by parts

A text, a series or a tensor is explained by its parts with POST /v1/explanations and method occlusion or shapley, the two methods such a model lists in explain_methods. Each part is compared with the same input with that part hidden, so no reference data is needed (options.background_source: "hidden_input").

InputA part isHidden by
text, tokensOne token. The special tokens a tokenizer adds are not parts; past 256 tokens, the last 256.The tokenizer's mask token, or else its unknown or padding token
sequenceOne step, or a stretch of steps: a series has at most 64 parts.The series' own average
tensorOne value, or a run of values: at most 256 parts.Zeros
audioA stretch of time: up to 20 of them, of equal length, fewer when the time an explanation may take affords fewer (options.parts[i].seconds).Silence
  • occlusion hides one part at a time and reports how far the score falls. auto is occlusion.
  • shapley shares the difference between the input and the input with every part hidden among the parts, over sampled orders in which they are revealed. shap is read as shapley. lime, and counterfactual: true, are method_not_applicable: a part is a position, not a feature to change.
  • Time. An explanation by parts stays within 40 seconds, counted from its start and including the building of each copy of the input with parts hidden. It times one copy first, and when the model is too slow to score every part that often, it splits the input into fewer, larger parts (options.parts_requested and options.budget_seconds say so) or takes fewer Shapley permutations (options.permutations, options.permutations_requested); Shapley walked from one order has no stderr. Copies of the input are built and scored 4 million values at a time.
  • What comes back. attributions are keyed feature[i], by position; top_features rank them with the token or the stretch as their value. options.parts describes each part (its key, label, position and token_id, or start and stop, its attribution, and a stderr for Shapley), with hidden_with, the score of the input and the hidden_score with everything hidden, which is also base_value.
  • A language model is explained as a classifier over its vocabulary: the target is the next token it predicts, or the token options.target_class names (as text or as its id).

A model whose answer is a whole tensor (generation, embedding), boxes, a mask or a group has nothing to attribute: its explain_methods is empty and an explanation is 422 method_not_applicable.

explanation = client.explanations.create(
    model="review-sentiment-v1", method="occlusion",
    input={"review": "the acting was great but the ending was awful."},
)
for part in explanation.options["parts"]:
    print(part["label"], round(part["attribution"], 3))
# the -0.0  acting -0.0 ... ending -0.814  was -0.057  awful -1.0  . -0.996
curl https://api.kaimei.ai/v1/explanations \
  -H "Authorization: Bearer $KAIMEI_API_KEY" -H "Content-Type: application/json" \
  -d '{"model": "review-sentiment-v1", "method": "occlusion",
       "input": {"review": "the acting was great but the ending was awful."}}'
201 CreatedResponse
{
  "object": "explanation",
  "id": "exp_87213b2ab80982dd168b",
  "model_id": "mdl_35636a1ada02058bf5fd",
  "method": "occlusion",
  "output": {
    "label": "negative",
    "class_index": 0,
    "probability": 0.999957,
    "target_label": "positive",
    "target_index": 1,
    "value": 4.26e-05,
    "name": "prediction"
  },
  "attributions": {
    "review[0]": -1.93e-05,
    "review[1]": -1.06e-05,
    …: …,
    "review[6]": -0.814334,
    "review[7]": -0.057247,
    "review[8]": -0.999601,
    "review[9]": -0.995548
  },
  "base_value": 0.978285,
  "top_features": [
    {
      "feature": "review[8]",
      "attribution": -0.999601,
      "value": "awful",
      "share": 0.3487,
      "direction": "negative",
      "rank": 1
    },
    {
      "feature": "review[9]",
      "attribution": -0.995548,
      "value": ".",
      "share": 0.3473,
      "direction": "negative",
      "rank": 2
    },
    …
  ],
  "options": {
    "feature": "review",
    "input_kind": "text",
    "parts": [
      {
        "key": "review[0]",
        "label": "the",
        "position": 0,
        "token_id": 54,
        "attribution": -1.93e-05
      },
      …,
      {
        "key": "review[8]",
        "label": "awful",
        "position": 8,
        "token_id": 5,
        "attribution": -0.999601
      },
      …
    ],
    "hidden_with": "the unknown token",
    "target": "positive",
    "score": 4.26e-05,
    "hidden_score": 0.978285,
    "background_source": "hidden_input"
  }
}

#Models with several inputs

A model can read a picture, a text, a series, a tensor or a recording beside other inputs: a photo and its caption, a series and a table of columns. Two options of POST /v1/explanations say what an explanation of it is of, and the model's profile says what can be asked for in explanations.

optionsExplainsRefused when
feature: "caption"That one input in detail (regions of a picture, tokens of a text, stretches of a series or a recording, pieces of a tensor), every other input held as given.400 unknown_feature for a name the model does not have; 400 method_not_applicable for a table column, or for anything on a table-only model
scope: "inputs"Every input beside the others: one number for each, saying how far the answer moves when that whole input is hidden. method is occlusion or shapley (auto and shap mean Shapley here).400 method_not_applicable for a model without such an input and at least one more, and with lime or gradcam; 400 too_many_features past 32 inputs, or when the time does not afford a run for each input and two more; 422 no_reference_population when a table column has nothing to be hidden with
neitherA table as a table. A model with one such input: that input in detail (a model of one picture and table columns answers with the picture's regions). A model of several pictures: its first. A model with several such inputs that are not all pictures: all its inputs, when that fits, and otherwise its first picture, or its first such input, in detail.Never for not fitting
  • How a whole input is hidden. As its own parts are: a text's tokens by the tokenizer's mask, unknown or padding token; a series by its own average; a tensor by zeros; a recording by silence; a photo by a blurred copy of itself (a thumbnail under 64 pixels a side by gray). A table column is hidden with its value in the model's reference row: the mean of at least 5 uploaded reference rows (the most common value for a category or a yes or no), or else of at least 5 logged predictions. A declared baseline comes first, when the feature can read it.
  • What comes back. attributions are keyed by input name. options says scope: "inputs", inputs (the names, in order), hidden_with_by_input (what each was hidden with, in a few words) and, when a column's reference row was read, reference_source and reference_rows (how many rows it was averaged over). top_features[].value is a column's own value, and a few words about anything larger. feature and scope together are 400 invalid_option, and counterfactual: true with scope is 422 method_not_applicable.
  • Shapley over whole inputs is exact when the model can be run that often: every way of hiding some of the inputs is scored, nothing is sampled, and the same request gets the same answer (options.exact: true, options.coalitions). Past that, orders are sampled as for the parts of one input (options.permutations, with a stderr for each input).
  • Pictures. With a picture in view, shapley, shap and auto run occlusion over its regions. gradcam and lime read one picture: the one options.feature names, or the first. On a model of several pictures Grad-CAM reads the last map made from that picture. An explanation of a picture says which in options.feature, with options.input_kind: "image".
# one number for each input
together = client.explanations.create(model="listing-quality", method="shapley",
                                      input=listing, options={"scope": "inputs"})
print(together.attributions)                          # {'photo': ..., 'caption': ..., 'price': ...}
print(together.options["hidden_with_by_input"])

# the caption alone, token by token, with the photo and the price as given
caption = client.explanations.create(model="listing-quality", method="occlusion",
                                     input=listing, options={"feature": "caption"})
optionsthe form of an explanation of all inputs
{
  "scope": "inputs",
  "inputs": ["photo", "caption", "price"],
  "hidden_with_by_input": {
    "photo": "a blurred copy of the picture",
    "caption": "the unknown token",
    "price": "40, the average of the reference rows"
  },
  "target": "good",
  "score": …,
  "hidden_score": …,
  "background_source": "hidden_inputs",
  "reference_source": "reference_data",
  "exact": true,
  "coalitions": 8
}

#Recordings

A feature of type: "audio" is a recording of samples numbers at sample_rate a second (16,000 when left out; shape: [samples] may give the length instead). It may hold 2,000,000 samples, at up to 384,000 a second. The client makes one for an input the model reads as a run of samples (see what Kaimei works out).

  • A value is a list of numbers, packed float32 ({"$b64", "dtype": "f32", "shape"}), or a WAV file as a data URL (data:audio/wav;base64,…).
  • A WAV file may be 12 MB: PCM of 8, 16, 24 or 32 bits, or 32- or 64-bit float, any number of channels (averaged to one), at any rate up to 768,000 samples a second (resampled to the feature's, linearly). How long it is at the feature's rate is worked out from its header first, so a file too long for the feature is refused before it is resampled, and a header whose block align is not its channels times its sample size is 400 invalid_input.
  • Length. A shorter recording is filled with silence at its end. A longer one is 400 invalid_input, saying how long the model listens: cut, it would not be what was sent.
  • Explained by stretches of time. Up to 20 of equal length (fewer when the time an explanation may take affords fewer), each hidden by silence, with occlusion or shapley; each part says its seconds. A model's agent is sent the recording as packed float32.

The profile lists audio among inputs, after a picture and before text, and the dashboard's input panel plays a recording, loads a sound file and draws its waveform.

client.models.predict("keyword-spotter", input={"waveform": samples})        # 16,000 numbers
client.models.predict("keyword-spotter", input={"waveform": "data:audio/wav;base64,UklGR…"})

explanation = client.explanations.create(model="keyword-spotter", method="occlusion",
                                         input={"waveform": samples})
for part in explanation.options["parts"][:3]:
    print(part["label"], part["attribution"])
# 0.00–0.05 s -0.000315  0.05–0.10 s -0.000314  0.10–0.15 s -0.000315
optionsan explanation of a keyword spotter, by stretches of time
{
  "feature": "waveform",
  "input_kind": "audio",
  "parts": [
    {
      "key": "waveform[0]",
      "label": "0.00–0.05 s",
      "start": 0,
      "stop": 800,
      "seconds": [0.0, 0.05],
      "attribution": -0.000315
    },
    {
      "key": "waveform[800]",
      "label": "0.05–0.10 s",
      "start": 800,
      "stop": 1600,
      "seconds": [0.05, 0.1],
      "attribution": -0.000314
    },
    …
  ],
  "hidden_with": "silence",
  "target": "yes",
  "score": 0.383514,
  "hidden_score": 0.389382,
  "background_source": "hidden_input"
}