Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions native/llama/llama.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,9 +336,12 @@ func (e *Engine) run(ctx context.Context, s *C.smol_ctx, tokens []C.int32_t, opt
if C.smol_is_eog(s, tok) {
return finish("eos", nil)
}
n := C.smol_token_piece(s, tok, (*C.char)(unsafe.Pointer(&piece[0])), C.int(len(piece)))
if n > 0 {
pending = append(pending, piece[:n]...)
var text []byte
text, piece = readPiece(piece, func(p []byte) int {
return int(C.smol_token_piece(s, tok, (*C.char)(unsafe.Pointer(&p[0])), C.int(len(p))))
})
if len(text) > 0 {
pending = append(pending, text...)
if text := validPrefix(&pending); text != "" {
select {
case out <- app.Token{Text: text}:
Expand Down
19 changes: 19 additions & 0 deletions native/llama/readpiece.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package llama

// pieceFunc fills p with a token's text. It returns the number of bytes
// written, or -(required size) if p is too small (llama_token_to_piece contract).
type pieceFunc func(p []byte) int

// readPiece returns the token text and the buffer to reuse for the next token.
// The buffer only grows when the token doesn't fit.
func readPiece(buf []byte, fill pieceFunc) (text, newBuf []byte) {
n := fill(buf)
if n < 0 {
buf = make([]byte, -n)
n = fill(buf)
}
if n <= 0 {
return nil, buf
}
return buf[:n], buf
}
40 changes: 40 additions & 0 deletions native/llama/readpiece_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package llama

import (
"bytes"
"testing"
)

func TestReadPieceGrowsOnNegativeReturn(t *testing.T) {
long := bytes.Repeat([]byte("="), 300)
calls := 0
fill := func(p []byte) int {
calls++
if len(p) < len(long) {
return -len(long)
}
return copy(p, long)
}
text, buf := readPiece(make([]byte, 256), fill)
if !bytes.Equal(text, long) {
t.Fatalf("got %d bytes, want %d", len(text), len(long))
}
if len(buf) != 300 || calls != 2 {
t.Fatalf("buf=%d calls=%d, want 300 and 2", len(buf), calls)
}
}

func TestReadPieceNoGrowForShortToken(t *testing.T) {
fill := func(p []byte) int { return copy(p, "hi") }
text, buf := readPiece(make([]byte, 256), fill)
if string(text) != "hi" || len(buf) != 256 {
t.Fatalf("text=%q buflen=%d", text, len(buf))
}
}

func TestReadPieceEmpty(t *testing.T) {
text, _ := readPiece(make([]byte, 256), func(p []byte) int { return 0 })
if len(text) != 0 {
t.Fatal("expected empty")
}
}
Loading