Qwen3.5 Chat (LLM no dispositivo)

Qwen3.5-0.8B e um modelo hibrido DeltaNet (atencao linear) + GatedAttention com 24 camadas (18 DeltaNet + 6 GatedAttention), quantizado para INT4 em MLX (GPU Metal) e INT8 em CoreML (Neural Engine). Roda em Mac via MLX ou em iPhone e Mac via CoreML com geracao de tokens em streaming. Projetado para voice pipelines onde um LLM no dispositivo fornece o "cerebro" entre ASR e TTS.

Pronto para Voice Pipeline

Qwen3.5 Chat integra-se com o VoicePipeline do SpeechCore como componente LLM em cadeias ASR → LLM → TTS. A arquitetura hibrida DeltaNet fornece atencao eficiente em tempo linear para contextos longos.

Inicio rapido

import Qwen3Chat

let chat = try await Qwen35MLXChat.fromPretrained()

// Single response
let response = try chat.generate("What is Swift?", systemPrompt: "Answer briefly.")
print(response)

// Streaming tokens
let stream = chat.chatStream("Tell me a joke", systemPrompt: "Be funny.")
for try await token in stream {
    print(token, terminator: "")
}

Arquitetura

Qwen3.5-0.8B e um modelo hibrido com 24 camadas: 18 camadas DeltaNet (atencao linear com recorrencia de regra delta gated e RMSNormGated) e 6 camadas GatedAttention (scaled dot-product attention padrao). O backend MLX roda inferencia na GPU Metal com pesos safetensors. O backend CoreML usa uma arquitetura de modelo duplo (prefill + decode) otimizada para o Neural Engine. Ambos suportam KV cache com prompt caching e sampling configuravel (temperatura, top-k, top-p, penalizacao de repeticao).

I/O do modelo

DirecaoNomeFormatoDescricao
Entradainput_ids[1, seq_len]IDs de token (Int32)
Entradaattention_mask[1, seq_len]Mascara de atencao (Int32)
Entradakv_cachepor camadaEstado do key-value cache
Saidalogits[1, 1, 151936]Logits do proximo token (Float16)
Saidakv_cache_outpor camadaKV cache atualizado

Variantes do modelo

VarianteQuantizacaoTamanhoComputacaoHuggingFace
Qwen3.5-0.8B ChatINT4418 MBGPU Metal (MLX)aufklarer/Qwen3.5-0.8B-Chat-MLX
Qwen3.5-0.8B ChatINT8981 MBNeural Engine (CoreML)aufklarer/Qwen3.5-0.8B-Chat-CoreML

Configuracao de sampling

let config = ChatSamplingConfig(
    temperature: 0.7,
    topK: 40,
    topP: 0.9,
    maxTokens: 128,
    repetitionPenalty: 1.1,
    disableThinking: false,
    maxThinkingTokens: 50
)
let response = try chat.generate("Explain gravity", sampling: config)
ParametroPadraoDescricao
temperature0.6Aleatoriedade (0 = greedy, 1 = criativo)
topK50Manter os K melhores candidatos
topP0.95Limiar de nucleus sampling
maxTokens512Maximo de tokens de resposta
repetitionPenalty1.1Penalizar tokens repetidos
disableThinkingfalsePular o modo de pensamento
maxThinkingTokens100Limitar tokens de pensamento

Conversa multi-turno

let chat = try await Qwen35MLXChat.fromPretrained()

let r1 = try chat.generate("My name is Alex", systemPrompt: "Remember the user's name.")
print(r1)  // "Nice to meet you, Alex!"

let r2 = try chat.generate("What's my name?")
print(r2)  // "Your name is Alex!"

chat.resetConversation()  // Clear history and KV cache

Gerenciamento de memoria

// Check memory state
print(chat.isLoaded)        // true
print(chat.memoryFootprint) // 438304768 (~418 MB)

// Free memory under pressure
chat.unload()
print(chat.isLoaded)        // false

// Reload when needed
let chat = try await Qwen35MLXChat.fromPretrained()
Dica de memoria para iOS

No iPhone, descarregar o LLM antes da inferencia TTS libera ~418 MB (MLX INT4) ou ~981 MB (CoreML INT8), evitando terminacao por jetsam ao rodar pipelines completos ASR → LLM → TTS.

Desempenho

DispositivoPrefillDecodeTokens/seg
M2 Max~50ms~65ms/tok~15 tok/s
iPhone 16 Pro~1.5s~450ms/tok~2.2 tok/s

Conversao

Os pesos MLX sao convertidos a partir do checkpoint original Qwen3.5-0.8B usando o script de conversao MLX. Os modelos CoreML usam um script de conversao separado para implantacao no Neural Engine. Pesos pre-convertidos estao disponiveis no HuggingFace em aufklarer/Qwen3.5-0.8B-Chat-MLX (INT4: 418 MB) e aufklarer/Qwen3.5-0.8B-Chat-CoreML (INT8: 981 MB).