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(messages: [
    ChatMessage(role: .system, content: "Answer briefly."),
    ChatMessage(role: .user, content: "What is Swift?")
])
print(response)

// Streaming tokens
let stream = chat.generateStream(messages: [
    ChatMessage(role: .system, content: "Be funny."),
    ChatMessage(role: .user, content: "Tell me a joke")
])
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
)
let response = try chat.generate(
    messages: [ChatMessage(role: .user, content: "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 history = [
    ChatMessage(role: .system, content: "Remember the user's name."),
    ChatMessage(role: .user, content: "My name is Alex"),
    ChatMessage(role: .assistant, content: "Nice to meet you, Alex!"),
    ChatMessage(role: .user, content: "What's my name?")
]
let response = try chat.generate(messages: history)
print(response)  // "Your name is Alex!"

chat.resetState()  // Clear inference state for a new conversation

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).

Inkling 2 Mini: MLX Swift + Core ML

MLX · Swift nativo suporta texto em streaming e imagens estáticas. Exporte especialistas em 4, 5 ou 8 bits, com atenção e vocabulário em 8 bits. As camadas repetidas partilham pesos e mantêm caches separadas. Valores padrão: 8.192 tokens de contexto e 1.024 patches por imagem.

Modelos exportados publicados: INT4 · INT5 · Core ML INT8

import Foundation
import Qwen3Chat

let model = try Inkling2Chat.fromDirectory(
    URL(fileURLWithPath: "/path/to/Inkling-2-Mini-MLX-4bit"))
for try await text in model.generateStream(
    messages: [.init(role: .user, content: "What is 2 + 2?")]) {
    print(text, terminator: "")
}
hf download aufklarer/Inkling-2-Mini-MLX-4bit \
  --local-dir /path/to/Inkling-2-Mini-MLX-4bit

speech inkling "What is 2 + 2?" \
  --model-dir /path/to/Inkling-2-Mini-MLX-4bit \
  --temperature 0 --max-tokens 512

speech inkling "Describe this image." \
  --model-dir /path/to/Inkling-2-Mini-MLX-4bit \
  --image photo.png --max-tokens 512
python scripts/export_inkling_mlx.py --stream-source --bits 4 \
  --output /path/to/Inkling-2-Mini-MLX-4bit

Core ML INT8

As exportações Core ML usam pesos de texto INT8, ativações FP32 e caches separadas para cada passagem por uma camada, além de pesos de visão FP16. Exporte localmente e selecione --backend coreml. A escolha das unidades de computação solicita uma localização; a execução no Neural Engine tem de ser medida.

Os pesos compilados ocupam 27,7 GB. Reserve 65 GiB de disco, incluindo a cache de execução. A geração na CPU demora minutos no M5 Pro de 48 GB testado; meça a latência da sua tarefa.

Num teste de depuração, a resposta a um prompt de 2032 tokens demorou 51,8 minutos na CPU (M5 Pro com 48 GB).

hf download aufklarer/Inkling-2-Mini-CoreML-INT8 \
  --local-dir /path/to/Inkling-2-Mini-CoreML-INT8 \
  --exclude '*.mlpackage/*'

speech inkling "What is 2 + 2?" \
  --backend coreml --coreml-compute-units cpu \
  --model-dir /path/to/Inkling-2-Mini-CoreML-INT8 \
  --temperature 0 --max-tokens 512
import Foundation
import Qwen3Chat

let model = try Inkling2CoreMLChat.fromDirectory(
    URL(fileURLWithPath: "/path/to/Inkling-2-Mini-CoreML-INT8"),
    computeUnits: .cpuOnly)
for try await text in model.generateStream(
    messages: [.init(role: .user, content: "What is 2 + 2?")]) {
    print(text, terminator: "")
}
python scripts/prepare_inkling_coreml_bridge.py
python scripts/export_inkling_coreml.py \
  --output /path/to/Inkling-2-Mini-CoreML-INT8

Core ML / INT8 / Swift

Swift nativo suporta texto em streaming e imagens estáticas. Exporte especialistas em 4, 5 ou 8 bits, com atenção e vocabulário em 8 bits. As camadas repetidas partilham pesos e mantêm caches separadas. Valores padrão: 8.192 tokens de contexto e 1.024 patches por imagem.
6 + 12 × 3 + 6 = 48 · θ[24] · State[48]
Use o Inkling para propor ações locais a partir de texto ou imagens. O exemplo valida JSON, ações permitidas e entradas necessárias, retornando clarify se a saída for inválida. Não executa ações.
Use o Inkling para propor ações locais a partir de texto ou imagens. O exemplo valida JSON, ações permitidas e entradas necessárias, retornando clarify se a saída for inválida. Não executa ações.
python3 scripts/examples/inkling2_decision.py \
  "Summarize this note: The train is delayed by ten minutes. The platform has changed to number four." \
  --model-dir /path/to/Inkling-2-Mini-MLX-5bit \
  --speech .build/release/speech
# {"action": "summarize", "validated": true, "fallback_reason": null}

Executar o exemplo de decisão

Imagens sintéticas exatas e respostas finais das 25 verificações de cada variante. Os casos selecionados não demonstram precisão geral.
Imagens sintéticas exatas e respostas finais das 25 verificações de cada variante. Os casos selecionados não demonstram precisão geral.

Utilização e detalhes da exportação · Swift / CLI / MLX