Tokenizer
#struct TokenizerThe tokenizer: it turns text into indices and back.
| Name | Type | Description |
|---|---|---|
kind | int | The kind. |
tokens | Vector<str> | The text of the tokens. |
scores | Vector<f64> | The scores, for SentencePiece. |
index | HashMap<str, int> | The index of each token. |
merges | HashMap<str, int> | The ranks of the BPE merges. |
merge_keys | Vector<str> | The merge keys. |
bos | int = -1 | The index of the beginning token; -1 means there is none. |
eos | int = -1 | The index of the end token. |
unk | int = 0 | The index of the unknown token. |
add_bos | bool = true | Add the beginning token when encoding. |
byte_ids | Vector<int> | The token index of each byte. |
b2u | Vector<int> | The byte to character map of byte level BPE. |
import ai.llm
import ai.tensor
func main:
mut tokenizer := llm.NewTokenizer(llm.TOK_BPE)
each text in ["a", "b", "c", "ab"]:
_ := tokenizer.AddToken(text, 0.0)
end
tokenizer.AddMerge("a", "b")
tokenizer.Finish()
tokenizer.add_bos = false
mut ids := tokenizer.Encode("abcab")
println tokenizer.Size(), ids.Len(), tokenizer.TokenText(ids.Get(0)), tokenizer.Decode(ids)
println llm.TOK_SPM, llm.ROPE_NORMAL, llm.ROPE_NEOX
mut config := llm.Config {
vocab = tokenizer.Size(),
dim = 8,
layers = 2,
heads = 2,
kv_heads = 1,
ff = 16,
ctx = 32
}
println config.HeadDim()
mut model := llm.RandomModel(config, 7)
mut cache := llm.NewKVCache(config)
println model.ok, model.layers.Len(), cache.ctx
mut logits := llm.Forward(model, cache, ids)
println tensor.ShapeString(logits), cache.len
mut last := llm.LogitsRow(logits, ids.Len() - 1)
greedy := llm.Greedy(logits, ids.Len() - 1)
println tensor.ShapeString(last), greedy == tensor.ArgMaxAll(last)
mut sampler := llm.NewSampler(1)
sampler.temperature = 0.8
sampler.top_k = 3
sampler.top_p = 0.9
sampler.repeat_penalty = 1.1
mut recent := Vector {} as Vector<int>
next := sampler.Sample(logits, ids.Len() - 1, recent)
println next >= 0 and next < tokenizer.Size()
cache.Reset()
generated := llm.GenerateIds(model, cache, ids, 4, sampler, -1)
println generated.Len()
cache.Reset()
text := llm.Generate(model, cache, tokenizer, "ab", 3, sampler)
println text.Len() > 0
tensor.Free(logits)
tensor.Free(last)
cache.Free()
model.Free()
tokenizer.Free()
end4 3 ab abcab 0 0 1 4 true 2 32 3x4 3 1x4 true true 4 true