Skip to content
Open
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
175 changes: 89 additions & 86 deletions Sources/AnyLanguageModel/Models/LlamaLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1705,16 +1705,13 @@ import Foundation
throw LlamaLanguageModelError.tokenizationFailed
}

let batchPointer = UnsafeMutablePointer<llama_batch>.allocate(capacity: 1)
batchPointer.initialize(to: llama_batch_init(Int32(options.batchSize), 0, 1))
defer {
llama_batch_free(batchPointer.pointee)
batchPointer.deinitialize(count: 1)
batchPointer.deallocate()
guard let batch = llama_batch_ext_init(context) else {
throw LlamaLanguageModelError.insufficientMemory
}
defer { llama_batch_ext_free(batch) }

let hasEncoder = try prepareInitialBatch(
batch: &batchPointer.pointee,
batch: batch,
promptTokens: promptTokens,
model: model!,
vocab: vocab,
Expand All @@ -1741,7 +1738,7 @@ import Foundation
vocab: vocab,
vocabSize: vocabSize,
sampler: samplerPointer,
batch: batchPointer,
batch: batch,
position: initialPosition,
maximumTokens: maxTokens,
endTokens: [],
Expand All @@ -1763,7 +1760,7 @@ import Foundation
let vocab: OpaquePointer
let vocabSize: Int
let sampler: UnsafeMutablePointer<llama_sampler>
let batch: UnsafeMutablePointer<llama_batch>
let batch: OpaquePointer
let tokenToTextFn: (Int) -> String?
let tokensExcludedFromRepetitionPenalty: Set<Int>
let endTokens: Set<Int>
Expand All @@ -1778,7 +1775,7 @@ import Foundation
vocab: OpaquePointer,
vocabSize: Int,
sampler: UnsafeMutablePointer<llama_sampler>,
batch: UnsafeMutablePointer<llama_batch>,
batch: OpaquePointer,
position: Int32,
maximumTokens: Int,
endTokens: Set<Int>? = nil,
Expand Down Expand Up @@ -1860,20 +1857,17 @@ import Foundation
try LlamaLifecycle.shared.stopIfExiting()
let llamaToken = llama_token(token)

batch.pointee.n_tokens = 1
batch.pointee.token[0] = llamaToken
batch.pointee.pos[0] = position
batch.pointee.n_seq_id[0] = 1
if let seqIds = batch.pointee.seq_id, let seqId = seqIds[0] {
seqId[0] = 0
}
batch.pointee.logits[0] = 1
let isFilled = LlamaLanguageModel.fillBatch(
batch,
with: CollectionOfOne(llamaToken),
at: position,
outputsLogits: true
)

position += 1
remainingTokens -= 1

let decodeResult = llama_decode(context, batch.pointee)
guard decodeResult == 0 else {
guard isFilled, llama_process(context, LLAMA_PROCESS_TYPE_DECODE, batch) == 0 else {
throw LlamaLanguageModelError.decodingFailed
}

Expand All @@ -1888,7 +1882,7 @@ import Foundation
// the sampler fetches logits, dropping the mask. Build a candidate
// array holding only the allowed tokens and run the sampler chain
// over it instead.
guard let logits = llama_get_logits_ith(context, batch.pointee.n_tokens - 1) else {
guard let logits = llama_get_logits_ith(context, -1) else {
return eosToken
}

Expand Down Expand Up @@ -1936,11 +1930,13 @@ import Foundation
sessionContextLock.unlock()

// Initialize batch
var batch = llama_batch_init(Int32(options.batchSize), 0, 1)
defer { llama_batch_free(batch) }
guard let batch = llama_batch_ext_init(context) else {
throw LlamaLanguageModelError.insufficientMemory
}
defer { llama_batch_ext_free(batch) }

let hasEncoder = try prepareInitialBatch(
batch: &batch,
batch: batch,
promptTokens: promptTokens,
model: model,
vocab: vocab,
Expand Down Expand Up @@ -1982,7 +1978,7 @@ import Foundation

// Sample the next token from the logits of the last decoded token.
// llama_sampler_sample also accepts the token into the sampler chain.
let nextToken = llama_sampler_sample(sampler, context, batch.n_tokens - 1)
let nextToken = llama_sampler_sample(sampler, context, -1)

// Check for end of sequence
if !counts.acceptToken(isEndOfGeneration: llama_vocab_is_eog(vocab, nextToken)) {
Expand All @@ -1997,19 +1993,16 @@ import Foundation
}

// Prepare batch for next token
batch.n_tokens = 1
batch.token[0] = nextToken
batch.pos[0] = n_cur
batch.n_seq_id[0] = 1
if let seq_ids = batch.seq_id, let seq_id = seq_ids[0] {
seq_id[0] = 0
}
batch.logits[0] = 1
let isFilled = Self.fillBatch(
batch,
with: CollectionOfOne(nextToken),
at: n_cur,
outputsLogits: true
)

n_cur += 1

let decodeResult = llama_decode(context, batch)
guard decodeResult == 0 else {
guard isFilled, llama_process(context, LLAMA_PROCESS_TYPE_DECODE, batch) == 0 else {
break
}
decodedTokens.append(nextToken)
Expand Down Expand Up @@ -2129,8 +2122,10 @@ import Foundation
}
defer { llama_sampler_free(samplerPtr) }

var batch = llama_batch_init(1, 0, 1)
defer { llama_batch_free(batch) }
guard let batch = llama_batch_ext_init(context) else {
throw LlamaLanguageModelError.insufficientMemory
}
defer { llama_batch_ext_free(batch) }

var n_cur: Int32 = Int32(pastPosition)
var sampleIndex: Int32 = -1
Expand All @@ -2156,18 +2151,16 @@ import Foundation
}
}

batch.n_tokens = 1
batch.token[0] = nextToken
batch.pos[0] = n_cur
batch.n_seq_id[0] = 1
if let seq_ids = batch.seq_id, let seq_id = seq_ids[0] {
seq_id[0] = 0
}
batch.logits[0] = 1
let isFilled = Self.fillBatch(
batch,
with: CollectionOfOne(nextToken),
at: n_cur,
outputsLogits: true
)

n_cur += 1

guard llama_decode(context, batch) == 0 else {
guard isFilled, llama_process(context, LLAMA_PROCESS_TYPE_DECODE, batch) == 0 else {
break
}
sampleIndex = 0
Expand Down Expand Up @@ -2213,7 +2206,7 @@ import Foundation
/// `insufficientMemory` if an encoder prompt exceeds the batch capacity, `encoderOnlyModel`
/// if the model cannot generate text, `encodingFailed` or `decodingFailed` on failure.
private func prepareInitialBatch(
batch: inout llama_batch,
batch: OpaquePointer,
promptTokens: [llama_token],
model: OpaquePointer,
vocab: OpaquePointer,
Expand All @@ -2230,26 +2223,18 @@ import Foundation
let hasEncoder = llama_model_has_encoder(model)
let hasDecoder = llama_model_has_decoder(model)

// Encoder models ingest the full prompt in a single llama_encode call.
// Encoder models ingest the full prompt in a single encode call.
guard !hasEncoder || (startIndex == 0 && promptTokens.count <= batchSize) else {
throw LlamaLanguageModelError.insufficientMemory
}

if hasEncoder {
// For encoder models, first encode the prompt
batch.n_tokens = Int32(promptTokens.count)
for i in 0 ..< promptTokens.count {
let idx = Int(i)
batch.token[idx] = promptTokens[idx]
batch.pos[idx] = Int32(i)
batch.n_seq_id[idx] = 1
if let seq_ids = batch.seq_id, let seq_id = seq_ids[idx] {
seq_id[0] = 0
}
batch.logits[idx] = 0
guard Self.fillBatch(batch, with: promptTokens, at: 0, outputsLogits: false) else {
throw LlamaLanguageModelError.insufficientMemory
}

guard llama_encode(context, batch) == 0 else {
guard llama_process(context, LLAMA_PROCESS_TYPE_ENCODE, batch) == 0 else {
throw LlamaLanguageModelError.encodingFailed
}

Expand All @@ -2260,16 +2245,15 @@ import Foundation
decoderStartToken = llama_vocab_bos(vocab)
}

batch.n_tokens = 1
batch.token[0] = decoderStartToken
batch.pos[0] = 0
batch.n_seq_id[0] = 1
if let seq_ids = batch.seq_id, let seq_id = seq_ids[0] {
seq_id[0] = 0
}
batch.logits[0] = 1

guard llama_decode(context, batch) == 0 else {
guard
Self.fillBatch(
batch,
with: CollectionOfOne(decoderStartToken),
at: 0,
outputsLogits: true
),
llama_process(context, LLAMA_PROCESS_TYPE_DECODE, batch) == 0
else {
throw LlamaLanguageModelError.decodingFailed
}
} else {
Expand All @@ -2282,27 +2266,21 @@ import Foundation
// Standard decoder-only model (most LLMs): feed the prompt in
// batch-sized chunks with absolute positions, requesting logits
// only for the final token.
let capacity = Int(batchSize)
// The batch holds at most the context's own batch size.
let capacity = min(Int(batchSize), Int(llama_n_batch(context)))
var start = startIndex
while start < promptTokens.count {
try LlamaLifecycle.shared.stopIfExiting()
let count = min(capacity, promptTokens.count - start)
batch.n_tokens = Int32(count)
for i in 0 ..< count {
batch.token[i] = promptTokens[start + i]
batch.pos[i] = Int32(start + i)
batch.n_seq_id[i] = 1
if let seq_ids = batch.seq_id, let seq_id = seq_ids[i] {
seq_id[0] = 0
}
batch.logits[i] = 0
}

if start + count == promptTokens.count {
batch.logits[count - 1] = 1
}

guard llama_decode(context, batch) == 0 else {
guard
Self.fillBatch(
batch,
with: promptTokens[start ..< start + count],
at: Int32(start),
outputsLogits: start + count == promptTokens.count
),
llama_process(context, LLAMA_PROCESS_TYPE_DECODE, batch) == 0
else {
throw LlamaLanguageModelError.decodingFailed
}
start += count
Expand All @@ -2312,6 +2290,31 @@ import Foundation
return hasEncoder
}

/// Refills `batch` with `tokens` at consecutive positions starting at `position`.
///
/// Logits are output for the last token only, and only when `outputsLogits` is set.
///
/// - Returns: `false` if `tokens` is empty or the batch cannot hold it.
private static func fillBatch(
_ batch: OpaquePointer,
with tokens: some Collection<llama_token>,
at position: llama_pos,
outputsLogits: Bool
) -> Bool {
llama_batch_ext_clear(batch)
var position = position
var lastIndex: Int32 = -1
for token in tokens {
lastIndex = llama_batch_ext_add_token(batch, 0, token)
guard lastIndex >= 0, llama_batch_ext_set_pos(batch, lastIndex, &position) else {
return false
}
position += 1
}
guard lastIndex >= 0 else { return false }
return !outputsLogits || llama_batch_ext_set_output_logits(batch, lastIndex, true)
}

private func formatPrompt(
requestContext: LanguageModelSession.RequestContext,
extraSystemMessage: String? = nil,
Expand Down
32 changes: 15 additions & 17 deletions Tests/AnyLanguageModelTests/LlamaLanguageModelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -443,21 +443,21 @@ import Testing
LlamaLanguageModel.makeSamplerChain(vocabularySize: llama_vocab_n_tokens(vocab), options: options)
)
defer { llama_sampler_free(sampler) }
var batch = llama_batch_init(Int32(promptTokens.count), 0, 1)
defer { llama_batch_free(batch) }
setBatch(&batch, tokens: promptTokens, startPosition: 0)
try #require(llama_decode(referenceContext, batch) == 0)
let batch = try #require(llama_batch_ext_init(referenceContext))
defer { llama_batch_ext_free(batch) }
try setBatch(batch, tokens: promptTokens, startPosition: 0)
try #require(llama_process(referenceContext, LLAMA_PROCESS_TYPE_DECODE, batch) == 0)
var referencePieces: [String] = []
var position = Int32(promptTokens.count)
for _ in 0 ..< maxTokens {
let token = llama_sampler_sample(sampler, referenceContext, batch.n_tokens - 1)
let token = llama_sampler_sample(sampler, referenceContext, -1)
if llama_vocab_is_eog(vocab, token) { break }
if let piece = piece(token, vocab: vocab) {
referencePieces.append(piece)
}
setBatch(&batch, tokens: [token], startPosition: position)
try setBatch(batch, tokens: [token], startPosition: position)
position += 1
try #require(llama_decode(referenceContext, batch) == 0)
try #require(llama_process(referenceContext, LLAMA_PROCESS_TYPE_DECODE, batch) == 0)
}

#expect(!referencePieces.isEmpty)
Expand Down Expand Up @@ -499,16 +499,14 @@ import Testing
return String(decoding: buffer.prefix(Int(count)).map { UInt8(bitPattern: $0) }, as: UTF8.self)
}

private func setBatch(_ batch: inout llama_batch, tokens: [llama_token], startPosition: Int32) {
batch.n_tokens = Int32(tokens.count)
for (index, token) in tokens.enumerated() {
batch.token[index] = token
batch.pos[index] = startPosition + Int32(index)
batch.n_seq_id[index] = 1
if let seqIDs = batch.seq_id, let seqID = seqIDs[index] {
seqID[0] = 0
}
batch.logits[index] = index == tokens.count - 1 ? 1 : 0
private func setBatch(_ batch: OpaquePointer, tokens: [llama_token], startPosition: Int32) throws {
llama_batch_ext_clear(batch)
for (offset, token) in tokens.enumerated() {
let index = llama_batch_ext_add_token(batch, 0, token)
try #require(index >= 0)
var position = startPosition + Int32(offset)
try #require(llama_batch_ext_set_pos(batch, index, &position))
try #require(llama_batch_ext_set_output_logits(batch, index, offset == tokens.count - 1))
}
}

Expand Down
Loading