Token Classifier
token_classifier.nr29 lines
token_classifier.nr· neuro
// A bag-of-tokens classifier. Integration example: token ids looked up in an embedding table
// with `.gather`, the sequence averaged away by name with `.mean(axis: seq)`, an `@` scoring
// pass, `.argmax` predictions compared with the labels, and the batch reordered by confidence
// with `.argsort` indices fed back into `.gather`. The exit code is the number of correct
// predictions.
func main() -> i32 {
// Four tokens in a two-dimensional embedding: 0 and 1 lean to class 0, 2 and 3 to class 1.
val embedding: Tensor<f32, [vocab: 4, dim: 2]> = [[1.0, 0.0], [2.0, 0.0], [0.0, 1.0], [0.0, 3.0]]
val tokens: Tensor<i32, [batch: 3, seq: 4]> = [[0, 1, 1, 0], [2, 3, 2, 3], [0, 3, 1, 2]]
val labels: Tensor<i32, [batch: 3]> = [0, 1, 1]
// `[batch, seq]` indices into `[vocab, dim]` rows give `[batch, seq, dim]`.
val embedded = embedding.gather(&tokens)
val pooled = embedded.mean(axis: seq)
val weights: Tensor<f32, [2, 2]> = [[1.0, 0.0], [0.0, 1.0]]
val scores = &pooled @ &weights
val predicted = (&scores).argmax(axis: 1)
println("pooled: {pooled[0, 0]} {pooled[1, 1]} {pooled[2, 0]}")
println("predicted: {predicted[0]} {predicted[1]} {predicted[2]}")
// The margin between the two scores orders the batch, most confident first.
val margin = (&scores).max(axis: 1) - (&scores).min(axis: 1)
val order = margin.argsort(axis: 0, descending: true)
val ranked = (&tokens).gather(&order)
println("most confident: {ranked[0, 0]} {ranked[0, 1]}, least: {order[2]}")
(predicted == labels).count() as i32
}
neuroc run token_classifier.nr
pooled: 1.5 2.0 0.75
predicted: 0 1 1
most confident: 2 3, least: 2