中文 English

Why Does a '35B' Model Weigh 56.8B? Qwen4-35B-A3B Day-1 Deep Dive: 20.5B Engram SSD Offload, Naive MLX 4-bit Collapse & 3-OS Auto-Config Scripts

Published: 2026-12-05 · Views --
AI LLM LLM Qwen Qwen4 MoE AI Agent 本地大模型 Local LLM Benchmark Architecture Architecture Troubleshooting Troubleshooting Pitfall Guide 深度评测 Automation Automation Windows 11 Ubuntu 26.04 macOS 27

Let’s start with a blunt warning from Day-1 local testing: released on December 4, 2026 under Apache 2.0, Alibaba’s Qwen4-35B-A3B might be the easiest model name in 2026 to miscalculate your VRAM budget on. Glance at 35B-A3B and the back-of-the-envelope math feels effortless: 35 billion total parameters, ~3 billion active per token (~3.8B), so a 4-bit quant should sit comfortably around 20 GB and glide straight onto a 24GB RTX 4090 or 24GB Apple Silicon MacBook.

Then you open the Hugging Face model card—or run ollama run qwen4—and reality hits like a brick. Ollama’s default qwen4:35b-a3b pull clocks in at 36GB–37GB, and Hugging Face’s Safetensors badge reports 57B params (56.8B exact, ~113.7 GB in BF16). Treat it like a plain 35B dense or MoE checkpoint on a 24GB machine and you immediately collide with four frustrating Day-1 failures: instant OOM crashes, half-speed decode crawling around 69 tok/s, broken gibberish on Apple Silicon after running a standard mlx_lm.convert -q 4-bit conversion, or infinite repetition loops the moment you toggle thinking off.

Cross-checking Qwen/Qwen4-35B-A3B’s config.json, README-tokenizer.md, the Hugging Face Day-0 engineering post, and Unsloth’s 11-dataset KLD evaluation reveals why: those extra 22.5 billion parameters aren’t doing heavy matrix math at all—20.5B of them form a static Layer-2 N-gram lookup dictionary (PLE / Engram) plus a 2B 1-layer Multi-Token Prediction (MTP) drafter. Once you leave that dictionary on your NVMe SSD or system RAM via memory mapping, 3-bit runs on just 18GB RAM, 4-bit flies on 24GB GPUs at 131–138 tok/s, and built-in MTP pushes desktop decode up to 127.7–224.0 tok/s. Below is the plain-English breakdown using 12 real screenshots and custom Huashu-Design diagrams, everyday analogies an elementary schooler can follow, and zero-dependency automation toolkits for Windows 11, Ubuntu 26.04, and macOS 27.

Original panoramic overview: Qwen4-35B-A3B 56.8B footprint mystery, Engram SSD offload, and four Day-1 setup traps

Figure 1: Original panoramic overview summarizing Qwen4-35B-A3B's true parameter split (35B core / 3.8B active + 20.5B Engram + 2B MTP), 1M native context, and the four Day-1 traps covered below.


1. Background: Why Qwen4-35B-A3B Broke the Internet—and Broke Local Rigs on Day 1

On December 4, 2026, following the mid-November debut of closed flagship Qwen4-Max, Alibaba's Qwen Team dropped the first open-weights release of the Qwen4 generation—Qwen4-35B-A3B—under a clean Apache 2.0 license across Hugging Face and ModelScope.

Authentic browser screenshot of Hugging Face Qwen/Qwen4-35B-A3B model card showing 57B params and Apache 2.0

Figure 2: Authentic screenshot of huggingface.co/Qwen/Qwen4-35B-A3B. Notice the Safetensors metadata on the right: 57B params despite the 35B-A3B label.

On capability per active FLOP, Qwen4-35B-A3B punches miles above its sub-50B weight class:

Authentic screenshot of Hugging Face launch blog Welcome Qwen 4: Cutting-edge intelligence on-device

Figure 3: Authentic screenshot of the Day-0 Hugging Face engineering post (huggingface.co/blog/qwen4) detailing collaborations across transformers, llama.cpp, vLLM, SGLang, and MLX.

Official Qwen4-35B-A3B benchmark chart comparing DeepSWE, Terminal Bench, NL2Repo, GPQA, and VideoIndex

Figure 4: Official 12-benchmark comparison chart from Qwen's model card showing Qwen4-35B-A3B outperforming much heavier baselines across agentic software engineering and multimodal understanding.


2. Symptoms: The Four Confusing Failures Local Adopters Hit Immediately

Within hours of weights going live, local-LLM forums and issue trackers lit up with four recurring failure reports:

Authentic screenshot of Ollama library page for qwen4 showing 36-37GB tag sizes and Agent launch commands

Figure 5: Authentic screenshot of ollama.com/library/qwen4. Ollama provides one-line launchers for Claude Code and OpenCode, though its default 36GB–37GB tag requires careful VRAM/KV tuning on 24GB hardware.

Authentic screenshot of OpenRouter page for qwen/qwen4-35b-a3b showing $0.04 input and $0.30 output pricing per 1M tokens

Figure 6: Authentic screenshot of openrouter.ai/qwen/qwen4-35b-a3b. If you want a zero-hardware cloud fallback, API pricing starts at $0.04/M input, $0.30/M output, and $0.003/M cache read.


3. How It Works (Grade-School Analogies + Exact config.json Blueprint)

You don't need graduate linear algebra to understand why Qwen4 behaves this way. Picture a small 24GB study desk, a heavy encyclopedia on the bookshelf next to you, and a 3-page sticky-note pad.

Original everyday analogy diagram explaining Qwen4 Engram SSD offloading, Gated DeltaNet noteboard, and sparse attention

Figure 7: Original everyday analogy diagram. Why putting the 20.5B trivia dictionary on the NVMe bookshelf frees your 24GB GPU desk for fast reasoning.

3.1 256 Specialists, 1 Lead Doctor & 4 Color-Coded Sticky Notes

Traditional dense models force every brain cell to fire for every word. Qwen4 works like a 35B-volume specialty clinic staffed by 256 routed specialists plus 1 permanent general practitioner: for each incoming word, the triage desk wakes up just 8 specialists + 1 shared doctor (~3.8B active parameters). Meanwhile, every token carries 4 parallel sticky-note streams (hc_count=4, bottleneck rank 256) mixed via learned gates before and after each block, keeping rich context intact without signal washout.

3.2 The 20.5B Ghost Weight: Moving the Encyclopedia Off Your Desk Onto the SSD Shelf

Normally, factual trivia ("What is Python's sorted() signature?", common 2- and 3-word idioms) hogs precious neural weights inside expensive GPU VRAM—like dumping a 200-pound encyclopedia straight onto your tiny study desk until it collapses.

Qwen4 isolates that memorized trivia inside Layer 2's 20.5B Per-Layer N-gram Embedding (PLE / Engram) table holding 10,000,000 bigram/trigram entries. For every token, the model reads just 16 rows (8 bigram lookups + 8 trigram lookups) and blends them with a tiny kernel-4 convolution. Because it is a read-only lookup table rather than heavy matrix multiplication, leaving it on your NVMe SSD or system RAM via --load-mode mmap --lazy-mode on -ot per_layer_token_embd=CPU cuts active RAM/VRAM usage by over 30%.

3.3 Remembering 1 Million Tokens Without Exploding KV Memory

Instead of scanning all 1,048,576 prior tokens at every layer, Qwen4's 40 decoder layers repeat a 4-layer cycle ten times (10 × (3 × Gated DeltaNet + 1 × Qwen Sparse Attention)):

Technical architecture blueprint strictly matching Qwen4-35B-A3B config.json across 40 decoder layers

Figure 8: Exact 40-layer blueprint verified against Hugging Face config.json, including the 27-layer ViT vision encoder, 4 residual streams, Layer-2 PLE, 10× hybrid blocks, and 1-layer MTP head.

3.4 Built-In 2B MTP: A Two-Word Draft Aide (Just Don't Get Greedy)

Every Qwen4 GGUF already embeds a 1-layer, ~2B Multi-Token Prediction (MTP) drafter (0.49–1.72 GB, no separate -md file needed). Like an assistant drafting the next two words for the boss to rubber-stamp in one pass, setting --spec-type draft-mtp --spec-draft-n-max 2 accelerates decode by 1.3x–1.4x (Mac M5 Max jumps from 91.2 to 127.7 tok/s on code; RTX 5090 jumps from 174.9 to 224.0 tok/s). Crank depth to 3 or 4, however, and rejected drafts drag prose speed down.


4. Root Cause Analysis & Verified Quantization Benchmarks

Authentic screenshot of Unsloth Qwen4 documentation showing Engram SSD offload and 18GB minimum RAM guidance

Figure 9: Authentic screenshot of Unsloth's Qwen4 guide (unsloth.ai/docs/models/qwen4) documenting SSD Engram offloading and hardware memory tiers.

Root Cause 1: Missing SSD Engram Flags & Cold MoE PCIe Thrashing

In unsloth/Qwen4-35B-A3B-GGUF, the final split shard isolates the Engram lookup table. Without mmap + lazy-mode + -ot per_layer_token_embd=CPU, runtimes try to force 11.5–21.8 GB of static trivia into scarce VRAM. Worse, when the model spills across PCIe onto system RAM without --moe-cache-mib, routed experts thrash across the bus—halving 24GB GPU decode from 131–138 tok/s down to 69–72 tok/s. On Ollama, missing OLLAMA_FLASH_ATTENTION=1 and OLLAMA_KV_CACHE_TYPE=q4_0 causes uncompressed KV bloat over long contexts.

Quant (Unsloth Dynamic v3.1) Engram Table Total Download Active Size w/ Engram on SSD Mean KLD (Lower=Better) 300-Task Accuracy (BF16: 95.3%)
UD-IQ2_XXS (12GB Tight) IQ4_NL / 11.5 GB 23.4 GB 11.9 GB 0.1935 93.6% (-1.8%)
UD-IQ3_XXS (18GB Laptop) IQ4_NL / 11.5 GB 28.7 GB 17.2 GB 0.0760 94.8% (-0.5%)
UD-Q3_K_XL (16–18GB GPU) IQ4_NL / 11.5 GB 30.9 GB 19.4 GB 0.0569 94.0% (-1.3%)
UD-IQ4_XS (24GB Pick) IQ4_NL / 11.5 GB 32.0 GB 20.5 GB 0.0532 95.2% (-0.1%)
UD-Q4_K_XL (32GB+ Sweet Spot) IQ4_NL / 11.5 GB 36.2 GB 24.7 GB 0.0375 95.0% (-0.3%)
UD-Q8_K_XL (Reference) Q8_0 / 21.8 GB 62.3 GB 40.5 GB 0.0171 94.8% (-0.5%)

Authentic screenshot of Hugging Face unsloth/Qwen4-35B-A3B-GGUF showing split quants and engram directory

Figure 10: Authentic screenshot of huggingface.co/unsloth/Qwen4-35B-A3B-GGUF/tree/main. Because the Engram table lives in its own shard (and engram/ directory), you can even pair UD-Q4_K_XL with a higher-precision Q8_0 Engram via --ple to cut KLD by another ~6%.

Root Cause 2: Why Naive MLX 4-bit Conversion Collapses (7.7x Worse KLD)

Qwen4 combines hyper-connection gates, Gated DeltaNet recurrences, and 256 sparse MoE routers—components that break catastrophically under uniform 4-bit compression. Unsloth's benchmark proves the gap:

Original quantization drift and hardware tier selector comparing naive MLX KLD collapse, MTP speedup, and 12GB-32GB+ tiers

Figure 11: Original quantization drift & hardware tier matrix. Highlights why naive MLX 4-bit fails and maps each RAM/VRAM budget to its optimal Qwen4 quant.

Root Cause 3: Tokenizer Mismatches, Sampling Drift & Conservative Video Defaults

Three software pitfalls trip up custom pipelines: (1) Qwen4's reference encoding_qwen4.py requires tiktoken and trust_remote_code=True to distinguish literal <think> text from protocol ID 248068; (2) Thinking mode (reasoning_effort="high" default) expects temperature=1.0, top_p=0.95, presence_penalty=0.0, whereas Non-Thinking mode (--reasoning off) and ultra-low quants (UD-IQ1_S to UD-IQ2_XXS) require temperature=0.7, top_p=0.80, presence_penalty=1.5 (plus min_p=0.01 on tiny quants) to prevent infinite loops; and (3) hour-long video understanding requires overriding video_preprocessor_config.json's longest_edge to 469762048 (~224K video tokens).


5. Complete Fix: Triage Matrix + Zero-Dependency 3-OS Toolkits + Agent Automation

Original vector troubleshooting matrix mapping Day-1 Qwen4 symptoms to root causes and exact CLI fixes

Figure 12: Original vector troubleshooting matrix linking all four Day-1 symptoms directly to their verified fixes.

5.1 Zero-Dependency Diagnostic & Auto-Config Scripts (Windows 11 / Ubuntu 26.04 / macOS 27)

To eliminate manual flag typos and hardware guesswork without relying on any third-party tools or cloud services, the toolkits below run natively on each OS to:

1. Windows 11 Toolkit (Native PowerShell 5.1 / 7+: qwen4_local_toolkit_windows11.ps1)

# ==============================================================================
# Qwen4-35B-A3B Local Diagnostic, Engram Offload & Auto-Config — Windows 11
# Zero third-party dependencies (native PowerShell 5.1 / 7+ only)
# Privacy Guard: Never emits hostnames, full non-loopback IPs, or raw API keys.
#
# Modes:
#   Human Interactive: powershell -ExecutionPolicy Bypass -File .\qwen4_local_toolkit_windows11.ps1
#   Agent Automated:   powershell -ExecutionPolicy Bypass -File .\qwen4_local_toolkit_windows11.ps1 -Auto -Json -Apply -ScaffoldAgent -Target .
# ==============================================================================
[CmdletBinding()]
param(
    [switch]$Auto,
    [switch]$Json,
    [ValidateSet("thinking", "fast")][string]$Mode = "thinking",
    [switch]$Apply,
    [switch]$ApplyOllama,
    [switch]$ScaffoldAgent,
    [string]$Target = "."
)

$ErrorActionPreference = "Stop"

# 1. Hardware & Storage Detection (Sanitized — no hostname or raw IP)
$cs = Get-CimInstance -ClassName Win32_ComputerSystem
$totalRamGB = [math]::Round($cs.TotalPhysicalMemory / 1GB, 1)

$gpuName = "none"
$vramGB = 0.0
$nvidiaSmi = Get-Command nvidia-smi -ErrorAction SilentlyContinue
if ($nvidiaSmi) {
    try {
        $smiOut = (& nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits 2>$null | Select-Object -First 1)
        if ($smiOut) {
            $parts = $smiOut -split ","
            $gpuName = $parts[0].Trim()
            $vramGB = [math]::Round(([double]$parts[1].Trim()) / 1024, 1)
        }
    } catch {}
}
if ($vramGB -eq 0) {
    $vc = Get-CimInstance -ClassName Win32_VideoController | Sort-Object AdapterRAM -Descending | Select-Object -First 1
    if ($vc) {
        $gpuName = $vc.Name
        if ($vc.AdapterRAM -gt 0) {
            $vramGB = [math]::Round($vc.AdapterRAM / 1GB, 1)
        }
    }
}

$targetResolved = (Resolve-Path -Path $Target -ErrorAction SilentlyContinue)
if (-not $targetResolved) { $targetResolved = Get-Location }
$driveLetter = ($targetResolved.Path.Substring(0, 1))
$psDrive = Get-PSDrive -Name $driveLetter -ErrorAction SilentlyContinue
$freeDiskGB = if ($psDrive) { [math]::Round($psDrive.Free / 1GB, 1) } else { 0.0 }

# Combined budget estimation for Engram SSD offload (24GB VRAM or RAM+VRAM pool)
$effectiveBudgetGB = if ($vramGB -ge 12) { $vramGB } else { [math]::Round($totalRamGB * 0.75 + $vramGB, 1) }

if ($effectiveBudgetGB -ge 32) {
    $tier = "Tier-A (32GB+)"
    $recQuant = "UD-Q4_K_XL"
    $activeFootprintGB = 24.7
    $downloadGB = 36.2
    $needSmallQuantGuard = $false
} elseif ($effectiveBudgetGB -ge 22) {
    $tier = "Tier-B (24GB)"
    $recQuant = "UD-IQ4_XS"
    $activeFootprintGB = 20.5
    $downloadGB = 32.0
    $needSmallQuantGuard = $false
} elseif ($effectiveBudgetGB -ge 16) {
    $tier = "Tier-C (16-18GB)"
    $recQuant = "UD-Q3_K_XL"
    $activeFootprintGB = 19.4
    $downloadGB = 30.9
    $needSmallQuantGuard = $false
} else {
    $tier = "Tier-D (12GB-Tight)"
    $recQuant = "UD-IQ2_XXS"
    $activeFootprintGB = 11.9
    $downloadGB = 23.4
    $needSmallQuantGuard = $true
}

$diskSpaceWarning = ($freeDiskGB -lt 45.0)

# 2. Local Runtime & Day-1 Trap Scan
$llamaServerCmd = Get-Command llama-server -ErrorAction SilentlyContinue
$ollamaCmd = Get-Command ollama -ErrorAction SilentlyContinue
$pythonCmd = Get-Command python -ErrorAction SilentlyContinue

$tiktokenInstalled = $false
if ($pythonCmd) {
    try {
        & python -c "import tiktoken" 2>$null
        if ($LASTEXITCODE -eq 0) { $tiktokenInstalled = $true }
    } catch {}
}

$ollamaFlashAttn = [Environment]::GetEnvironmentVariable("OLLAMA_FLASH_ATTENTION", "User")
if (-not $ollamaFlashAttn) { $ollamaFlashAttn = $env:OLLAMA_FLASH_ATTENTION }
$ollamaKvType = [Environment]::GetEnvironmentVariable("OLLAMA_KV_CACHE_TYPE", "User")
if (-not $ollamaKvType) { $ollamaKvType = $env:OLLAMA_KV_CACHE_TYPE }
$moeCacheMib = [Environment]::GetEnvironmentVariable("LLAMA_ARG_MOE_CACHE_MIB", "User")
if (-not $moeCacheMib) { $moeCacheMib = $env:LLAMA_ARG_MOE_CACHE_MIB }

$ollamaKvBloatTrap = ($null -ne $ollamaCmd) -and (($ollamaFlashAttn -ne "1") -or ([string]::IsNullOrWhiteSpace($ollamaKvType)))
$staleBaseUrlTrap = (-not [string]::IsNullOrWhiteSpace($env:OPENAI_BASE_URL)) -and ($env:OPENAI_BASE_URL -notmatch "localhost")

# 3. Interactive Human Prompt if not -Auto
if (-not $Auto) {
    Write-Host "=== Qwen4-35B-A3B Windows 11 Local Triage ===" -ForegroundColor Cyan
    Write-Host "Hardware Tier: $tier | Recommended Quant: $recQuant ($activeFootprintGB GB active / $downloadGB GB download)"
    if (-not $Apply) {
        $ansApply = Read-Host "Generate local Qwen4 launcher & sampling presets under ~\.qwen4-local? [Y/n]"
        if ($ansApply -eq "" -or $ansApply -match "^[Yy]") { $Apply = $true }
    }
    if ($ollamaCmd -and -not $ApplyOllama) {
        $ansOllama = Read-Host "Persist Ollama FlashAttention + q4_0 KV cache + 4096MiB MoE cache env vars? [y/N]"
        if ($ansOllama -match "^[Yy]") { $ApplyOllama = $true }
    }
    if (-not $ScaffoldAgent) {
        $ansAgent = Read-Host "Scaffold local Qwen4 agent profile in Target directory? [y/N]"
        if ($ansAgent -match "^[Yy]") { $ScaffoldAgent = $true }
    }
}

# 4. Apply Launchers & Sampling Presets Safely
$qwenDir = Join-Path $HOME ".qwen4-local"
$launcherCreated = $false
$presetsCreated = $false
$ollamaEnvApplied = $false
$agentScaffolded = $false
$backupFile = "none"

if ($Apply) {
    if (-not (Test-Path $qwenDir)) { New-Item -ItemType Directory -Path $qwenDir -Force | Out-Null }

    $minPVal = if ($needSmallQuantGuard) { "0.01" } else { "0.0" }
    $moeArg = if ($vramGB -ge 8) { "--moe-cache-mib 4096" } else { "" }

    $thinkingScript = @"
# Auto-generated Qwen4-35B-A3B Thinking Launcher (Engram SSD Offload + MTP depth=2)
`$ErrorActionPreference = "Stop"
llama-server -hf "unsloth/Qwen4-35B-A3B-GGUF:$recQuant" ``
  --host localhost --port 8081 ``
  --load-mode mmap --lazy-mode on -ot per_layer_token_embd=CPU ``
  --spec-type draft-mtp --spec-draft-n-max 2 ``
  $moeArg -fa on -c 65536 ``
  --temp 1.0 --top-p 0.95 --top-k 20 --min-p $minPVal
"@
    $fastScript = @"
# Auto-generated Qwen4-35B-A3B Non-Thinking Fast Launcher (Anti-Loop Sampling)
`$ErrorActionPreference = "Stop"
llama-server -hf "unsloth/Qwen4-35B-A3B-GGUF:$recQuant" ``
  --host localhost --port 8081 ``
  --load-mode mmap --lazy-mode on -ot per_layer_token_embd=CPU ``
  --spec-type draft-mtp --spec-draft-n-max 2 ``
  --reasoning off $moeArg -fa on -c 65536 ``
  --temp 0.7 --top-p 0.80 --top-k 20 --min-p $minPVal --presence-penalty 1.5
"@
    $thinkingPath = Join-Path $qwenDir "launch-qwen4-thinking.ps1"
    $fastPath = Join-Path $qwenDir "launch-qwen4-fast.ps1"
    if (Test-Path $thinkingPath) {
        $backupFile = "$thinkingPath.bak.$(Get-Date -Format 'yyyyMMddHHmmss')"
        Copy-Item $thinkingPath $backupFile -Force
    }
    Set-Content -Path $thinkingPath -Value $thinkingScript -Encoding UTF8
    Set-Content -Path $fastPath -Value $fastScript -Encoding UTF8
    $launcherCreated = $true

    $presetsObj = [ordered]@{
        model = "unsloth/Qwen4-35B-A3B-GGUF:$recQuant"
        local_openai_base_url = "http://localhost:8081/v1"
        thinking_mode = [ordered]@{
            reasoning_effort = "high"
            preserve_thinking = $true
            temperature = 1.0
            top_p = 0.95
            top_k = 20
            min_p = [double]$minPVal
            presence_penalty = 0.0
            repetition_penalty = 1.0
        }
        non_thinking_mode = [ordered]@{
            reasoning_effort = "off"
            temperature = 0.7
            top_p = 0.80
            top_k = 20
            min_p = [double]$minPVal
            presence_penalty = 1.5
            repetition_penalty = 1.0
        }
        long_video_preprocessor = [ordered]@{
            longest_edge = 469762048
            shortest_edge = 4096
            approx_video_tokens = 224000
        }
        mtp_speculative = [ordered]@{
            spec_type = "draft-mtp"
            spec_draft_n_max = 2
        }
    }
    $presetsObj | ConvertTo-Json -Depth 5 | Set-Content -Path (Join-Path $qwenDir "qwen4-sampling-presets.json") -Encoding UTF8
    $presetsCreated = $true
}

if ($ApplyOllama) {
    [Environment]::SetEnvironmentVariable("OLLAMA_FLASH_ATTENTION", "1", "User")
    [Environment]::SetEnvironmentVariable("OLLAMA_KV_CACHE_TYPE", "q4_0", "User")
    [Environment]::SetEnvironmentVariable("LLAMA_ARG_MOE_CACHE_MIB", "4096", "User")
    [Environment]::SetEnvironmentVariable("LLAMA_ARG_MOE_CACHE_CPU_SHARE", "0.5", "User")
    $ollamaEnvApplied = $true
}

if ($ScaffoldAgent) {
    $agentDir = Join-Path $targetResolved.Path ".claude\agents"
    if (-not (Test-Path $agentDir)) { New-Item -ItemType Directory -Path $agentDir -Force | Out-Null }
    $agentMd = @"
---
name: qwen4-local-worker
description: Local Qwen4-35B-A3B worker routed to localhost:8081 with Engram SSD offload and MTP depth=2.
---
Use local OpenAI-compatible endpoint http://localhost:8081/v1 (model: Qwen4-35B-A3B).
Keep reasoning_effort=low for quick file reads and high for architecture or multi-file refactors.
"@
    Set-Content -Path (Join-Path $agentDir "qwen4-local-worker.md") -Value $agentMd -Encoding UTF8
    $agentScaffolded = $true
}

$result = [ordered]@{
    platform = "Windows 11"
    ram_gb = $totalRamGB
    gpu_name = $gpuName
    vram_gb = $vramGB
    free_disk_gb = $freeDiskGB
    recommended_tier = $tier
    recommended_quant = $recQuant
    active_footprint_gb = $activeFootprintGB
    download_size_gb = $downloadGB
    llama_server_found = ($null -ne $llamaServerCmd)
    ollama_found = ($null -ne $ollamaCmd)
    tiktoken_installed = $tiktokenInstalled
    disk_space_warning = $diskSpaceWarning
    ollama_kv_bloat_trap = $ollamaKvBloatTrap
    stale_base_url_trap = $staleBaseUrlTrap
    small_quant_anti_loop_needed = $needSmallQuantGuard
    launcher_created = $launcherCreated
    presets_created = $presetsCreated
    ollama_env_applied = $ollamaEnvApplied
    agent_scaffolded = $agentScaffolded
    backup_file = $backupFile
}

if ($Json) {
    $result | ConvertTo-Json -Depth 4
} else {
    Write-Host "`n=== Qwen4-35B-A3B Diagnostic Summary (Windows 11 · Sanitized) ===" -ForegroundColor Green
    Write-Host "RAM / GPU / VRAM:        ${totalRamGB} GB RAM | ${gpuName} (${vramGB} GB VRAM)"
    Write-Host "Free Disk on Target:     ${freeDiskGB} GB (warning=${diskSpaceWarning})"
    Write-Host "Tier / Recommended:      ${tier} -> ${recQuant} (${activeFootprintGB} GB active)"
    Write-Host "Runtimes:                llama-server=$($result.llama_server_found) | ollama=$($result.ollama_found) | tiktoken=${tiktokenInstalled}"
    Write-Host "Traps:                   OllamaKVBloat=${ollamaKvBloatTrap} | StaleBaseURL=${staleBaseUrlTrap} | AntiLoopGuard=${needSmallQuantGuard}"
    Write-Host "Applied:                 launchers=${launcherCreated} | presets=${presetsCreated} | ollamaEnv=${ollamaEnvApplied} | agent=${agentScaffolded}"
}

Human interactive run:

powershell -ExecutionPolicy Bypass -File .\qwen4_local_toolkit_windows11.ps1

2. Ubuntu 26.04 Toolkit (Native GNU Bash: qwen4_local_toolkit_ubuntu2604.sh)

#!/usr/bin/env bash
# ==============================================================================
# Qwen4-35B-A3B Local Diagnostic, Engram Offload & Auto-Config — Ubuntu 26.04
# Zero third-party dependencies (GNU bash, awk, grep, sed, free, df, tr)
# Privacy Guard: Never emits hostnames, full non-loopback IPs, or raw API keys.
#
# Modes:
#   Human Interactive: bash ./qwen4_local_toolkit_ubuntu2604.sh
#   Agent Automated:   bash ./qwen4_local_toolkit_ubuntu2604.sh --auto --json --apply --scaffold-agent --target .
# ==============================================================================
set -euo pipefail

AUTO=0
JSON_MODE=0
APPLY=0
APPLY_OLLAMA=0
SCAFFOLD_AGENT=0
TARGET_DIR="."

while [[ $# -gt 0 ]]; do
  case "$1" in
    --auto) AUTO=1; shift ;;
    --json) JSON_MODE=1; shift ;;
    --apply) APPLY=1; shift ;;
    --apply-ollama) APPLY_OLLAMA=1; shift ;;
    --scaffold-agent) SCAFFOLD_AGENT=1; shift ;;
    --target) TARGET_DIR="${2:-.}"; shift 2 ;;
    -h|--help)
      cat <<'EOF'
Usage: bash qwen4_local_toolkit_ubuntu2604.sh [options]
  --auto            Non-interactive mode for AI Agents
  --json            Emit sanitized JSON output
  --apply           Generate ~/.qwen4-local launchers & sampling presets
  --apply-ollama    Write ~/.qwen4-local/ollama-override.conf for systemd
  --scaffold-agent  Write .claude/agents/qwen4-local-worker.md in --target
  --target <dir>    Target workspace directory (default: .)
EOF
      exit 0
      ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

# 1. Hardware & Disk Detection (Sanitized)
RAM_KB="$(awk '/MemTotal:/ {print $2}' /proc/meminfo)"
RAM_GB="$(awk -v k="$RAM_KB" 'BEGIN {printf "%.1f", k/1024/1024}')"

GPU_NAME="none"
VRAM_GB="0.0"
if command -v nvidia-smi >/dev/null 2>&1; then
  SMI_LINE="$(nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits 2>/dev/null | head -n 1 || true)"
  if [[ -n "$SMI_LINE" ]]; then
    GPU_NAME="$(echo "$SMI_LINE" | awk -F',' '{gsub(/^[ \t]+|[ \t]+$/, "", $1); print $1}')"
    VRAM_MB="$(echo "$SMI_LINE" | awk -F',' '{gsub(/^[ \t]+|[ \t]+$/, "", $2); print $2}')"
    VRAM_GB="$(awk -v m="${VRAM_MB:-0}" 'BEGIN {printf "%.1f", m/1024}')"
  fi
fi

mkdir -p "$TARGET_DIR" 2>/dev/null || true
FREE_DISK_KB="$(df -Pk "$TARGET_DIR" | awk 'NR==2 {print $4}')"
FREE_DISK_GB="$(awk -v k="${FREE_DISK_KB:-0}" 'BEGIN {printf "%.1f", k/1024/1024}')"

BUDGET_GB="$(awk -v v="$VRAM_GB" -v r="$RAM_GB" 'BEGIN {if (v >= 12) printf "%.1f", v; else printf "%.1f", r*0.75 + v}')"

TIER="Tier-D (12GB-Tight)"
REC_QUANT="UD-IQ2_XXS"
ACTIVE_GB="11.9"
DL_GB="23.4"
SMALL_QUANT_GUARD="true"

if awk -v b="$BUDGET_GB" 'BEGIN {exit !(b >= 32)}'; then
  TIER="Tier-A (32GB+)"
  REC_QUANT="UD-Q4_K_XL"
  ACTIVE_GB="24.7"
  DL_GB="36.2"
  SMALL_QUANT_GUARD="false"
elif awk -v b="$BUDGET_GB" 'BEGIN {exit !(b >= 22)}'; then
  TIER="Tier-B (24GB)"
  REC_QUANT="UD-IQ4_XS"
  ACTIVE_GB="20.5"
  DL_GB="32.0"
  SMALL_QUANT_GUARD="false"
elif awk -v b="$BUDGET_GB" 'BEGIN {exit !(b >= 16)}'; then
  TIER="Tier-C (16-18GB)"
  REC_QUANT="UD-Q3_K_XL"
  ACTIVE_GB="19.4"
  DL_GB="30.9"
  SMALL_QUANT_GUARD="false"
fi

DISK_WARN="false"
if awk -v d="$FREE_DISK_GB" 'BEGIN {exit !(d < 45)}'; then
  DISK_WARN="true"
fi

# 2. Local Runtime & Trap Scan
LLAMA_FOUND="false"; command -v llama-server >/dev/null 2>&1 && LLAMA_FOUND="true"
OLLAMA_FOUND="false"; command -v ollama >/dev/null 2>&1 && OLLAMA_FOUND="true"
TIKTOKEN_FOUND="false"
if command -v python3 >/dev/null 2>&1 && python3 -c "import tiktoken" >/dev/null 2>&1; then
  TIKTOKEN_FOUND="true"
fi

OLLAMA_KV_BLOAT_TRAP="false"
if [[ "$OLLAMA_FOUND" == "true" ]]; then
  if [[ "${OLLAMA_FLASH_ATTENTION:-}" != "1" || -z "${OLLAMA_KV_CACHE_TYPE:-}" ]]; then
    OLLAMA_KV_BLOAT_TRAP="true"
  fi
fi

STALE_BASE_URL_TRAP="false"
if [[ -n "${OPENAI_BASE_URL:-}" && ! "${OPENAI_BASE_URL}" =~ localhost ]]; then
  STALE_BASE_URL_TRAP="true"
fi

# 3. Interactive Human Prompt
if (( AUTO == 0 )); then
  echo "=== Qwen4-35B-A3B Ubuntu 26.04 Local Triage ==="
  echo "Hardware Tier: ${TIER} | Recommended Quant: ${REC_QUANT} (${ACTIVE_GB} GB active / ${DL_GB} GB download)"
  if (( APPLY == 0 )); then
    read -r -p "Generate local Qwen4 launchers & presets in ~/.qwen4-local? [Y/n] " ans_apply
    if [[ -z "$ans_apply" || "$ans_apply" =~ ^[Yy]$ ]]; then APPLY=1; fi
  fi
  if [[ "$OLLAMA_FOUND" == "true" && $APPLY_OLLAMA -eq 0 ]]; then
    read -r -p "Generate Ollama systemd override snippet (~/.qwen4-local/ollama-override.conf)? [y/N] " ans_ol
    if [[ "$ans_ol" =~ ^[Yy]$ ]]; then APPLY_OLLAMA=1; fi
  fi
  if (( SCAFFOLD_AGENT == 0 )); then
    read -r -p "Scaffold local Qwen4 worker profile in target directory? [y/N] " ans_ag
    if [[ "$ans_ag" =~ ^[Yy]$ ]]; then SCAFFOLD_AGENT=1; fi
  fi
fi

# 4. Apply Configs Safely
QWEN_DIR="${HOME}/.qwen4-local"
LAUNCHER_CREATED="false"
PRESETS_CREATED="false"
OLLAMA_CONF_CREATED="false"
AGENT_SCAFFOLDED="false"
BACKUP_FILE="none"

if (( APPLY == 1 )); then
  mkdir -p "$QWEN_DIR"
  MIN_P="0.0"; [[ "$SMALL_QUANT_GUARD" == "true" ]] && MIN_P="0.01"
  MOE_ARG=""
  if awk -v v="$VRAM_GB" 'BEGIN {exit !(v >= 8)}'; then
    MOE_ARG="--moe-cache-mib 4096"
  fi

  THINK_SH="${QWEN_DIR}/launch-qwen4-thinking.sh"
  FAST_SH="${QWEN_DIR}/launch-qwen4-fast.sh"
  if [[ -f "$THINK_SH" ]]; then
    BACKUP_FILE="${THINK_SH}.bak.$(date +%Y%m%d%H%M%S)"
    cp "$THINK_SH" "$BACKUP_FILE"
  fi

  cat > "$THINK_SH" <<EOF
#!/usr/bin/env bash
set -euo pipefail
exec llama-server -hf "unsloth/Qwen4-35B-A3B-GGUF:${REC_QUANT}" \\
  --host localhost --port 8081 \\
  --load-mode mmap --lazy-mode on -ot per_layer_token_embd=CPU \\
  --spec-type draft-mtp --spec-draft-n-max 2 \\
  ${MOE_ARG} -fa on -c 65536 \\
  --temp 1.0 --top-p 0.95 --top-k 20 --min-p ${MIN_P}
EOF

  cat > "$FAST_SH" <<EOF
#!/usr/bin/env bash
set -euo pipefail
exec llama-server -hf "unsloth/Qwen4-35B-A3B-GGUF:${REC_QUANT}" \\
  --host localhost --port 8081 \\
  --load-mode mmap --lazy-mode on -ot per_layer_token_embd=CPU \\
  --spec-type draft-mtp --spec-draft-n-max 2 \\
  --reasoning off ${MOE_ARG} -fa on -c 65536 \\
  --temp 0.7 --top-p 0.80 --top-k 20 --min-p ${MIN_P} --presence-penalty 1.5
EOF
  chmod +x "$THINK_SH" "$FAST_SH"
  LAUNCHER_CREATED="true"

  cat > "${QWEN_DIR}/qwen4-sampling-presets.json" <<EOF
{
  "model": "unsloth/Qwen4-35B-A3B-GGUF:${REC_QUANT}",
  "local_openai_base_url": "http://localhost:8081/v1",
  "thinking_mode": {
    "reasoning_effort": "high",
    "preserve_thinking": true,
    "temperature": 1.0,
    "top_p": 0.95,
    "top_k": 20,
    "min_p": ${MIN_P},
    "presence_penalty": 0.0,
    "repetition_penalty": 1.0
  },
  "non_thinking_mode": {
    "reasoning_effort": "off",
    "temperature": 0.7,
    "top_p": 0.80,
    "top_k": 20,
    "min_p": ${MIN_P},
    "presence_penalty": 1.5,
    "repetition_penalty": 1.0
  },
  "long_video_preprocessor": {
    "longest_edge": 469762048,
    "shortest_edge": 4096,
    "approx_video_tokens": 224000
  },
  "mtp_speculative": {
    "spec_type": "draft-mtp",
    "spec_draft_n_max": 2
  }
}
EOF
  PRESETS_CREATED="true"
fi

if (( APPLY_OLLAMA == 1 )); then
  mkdir -p "$QWEN_DIR"
  cat > "${QWEN_DIR}/ollama-override.conf" <<'EOF'
# Copy to /etc/systemd/system/ollama.service.d/override.conf and run:
#   sudo systemctl daemon-reload && sudo systemctl restart ollama
[Service]
Environment="OLLAMA_FLASH_ATTENTION=1"
Environment="OLLAMA_KV_CACHE_TYPE=q4_0"
Environment="LLAMA_ARG_MOE_CACHE_MIB=4096"
Environment="LLAMA_ARG_MOE_CACHE_CPU_SHARE=0.5"
EOF
  OLLAMA_CONF_CREATED="true"
fi

if (( SCAFFOLD_AGENT == 1 )); then
  mkdir -p "${TARGET_DIR}/.claude/agents"
  cat > "${TARGET_DIR}/.claude/agents/qwen4-local-worker.md" <<'EOF'
---
name: qwen4-local-worker
description: Local Qwen4-35B-A3B worker routed to localhost:8081 with Engram SSD offload and MTP depth=2.
---
Use local OpenAI-compatible endpoint http://localhost:8081/v1 (model: Qwen4-35B-A3B).
Keep reasoning_effort=low for quick file reads and high for architecture or multi-file refactors.
EOF
  AGENT_SCAFFOLDED="true"
fi

if (( JSON_MODE == 1 )); then
  cat <<EOF
{
  "platform": "Ubuntu 26.04",
  "ram_gb": ${RAM_GB},
  "gpu_name": "${GPU_NAME}",
  "vram_gb": ${VRAM_GB},
  "free_disk_gb": ${FREE_DISK_GB},
  "recommended_tier": "${TIER}",
  "recommended_quant": "${REC_QUANT}",
  "active_footprint_gb": ${ACTIVE_GB},
  "download_size_gb": ${DL_GB},
  "llama_server_found": ${LLAMA_FOUND},
  "ollama_found": ${OLLAMA_FOUND},
  "tiktoken_installed": ${TIKTOKEN_FOUND},
  "disk_space_warning": ${DISK_WARN},
  "ollama_kv_bloat_trap": ${OLLAMA_KV_BLOAT_TRAP},
  "stale_base_url_trap": ${STALE_BASE_URL_TRAP},
  "small_quant_anti_loop_needed": ${SMALL_QUANT_GUARD},
  "launcher_created": ${LAUNCHER_CREATED},
  "presets_created": ${PRESETS_CREATED},
  "ollama_override_created": ${OLLAMA_CONF_CREATED},
  "agent_scaffolded": ${AGENT_SCAFFOLDED},
  "backup_file": "${BACKUP_FILE}"
}
EOF
else
  echo ""
  echo "=== Qwen4-35B-A3B Diagnostic Summary (Ubuntu 26.04 · Sanitized) ==="
  echo "RAM / GPU / VRAM:        ${RAM_GB} GB RAM | ${GPU_NAME} (${VRAM_GB} GB VRAM)"
  echo "Free Disk on Target:     ${FREE_DISK_GB} GB (warning=${DISK_WARN})"
  echo "Tier / Recommended:      ${TIER} -> ${REC_QUANT} (${ACTIVE_GB} GB active)"
  echo "Runtimes:                llama-server=${LLAMA_FOUND} | ollama=${OLLAMA_FOUND} | tiktoken=${TIKTOKEN_FOUND}"
  echo "Traps:                   OllamaKVBloat=${OLLAMA_KV_BLOAT_TRAP} | StaleBaseURL=${STALE_BASE_URL_TRAP} | AntiLoopGuard=${SMALL_QUANT_GUARD}"
  echo "Applied:                 launchers=${LAUNCHER_CREATED} | presets=${PRESETS_CREATED} | ollamaConf=${OLLAMA_CONF_CREATED} | agent=${AGENT_SCAFFOLDED}"
fi

Human interactive run:

chmod +x ./qwen4_local_toolkit_ubuntu2604.sh && bash ./qwen4_local_toolkit_ubuntu2604.sh

3. macOS 27 Toolkit (Native Zsh: qwen4_local_toolkit_macos27.zsh)

#!/usr/bin/env zsh
# ==============================================================================
# Qwen4-35B-A3B Local Diagnostic, Engram/MLX Guard & Auto-Config — macOS 27
# Zero third-party dependencies (macOS built-in zsh, sysctl, df, awk, grep, sed)
# Privacy Guard: Never emits hostnames, full non-loopback IPs, or raw API keys.
#
# Modes:
#   Human Interactive: zsh ./qwen4_local_toolkit_macos27.zsh
#   Agent Automated:   zsh ./qwen4_local_toolkit_macos27.zsh --auto --json --apply --scaffold-agent --target .
# ==============================================================================
set -euo pipefail

AUTO=0
JSON_MODE=0
APPLY=0
APPLY_OLLAMA=0
SCAFFOLD_AGENT=0
TARGET_DIR="."

while [[ $# -gt 0 ]]; do
  case "$1" in
    --auto) AUTO=1; shift ;;
    --json) JSON_MODE=1; shift ;;
    --apply) APPLY=1; shift ;;
    --apply-ollama) APPLY_OLLAMA=1; shift ;;
    --scaffold-agent) SCAFFOLD_AGENT=1; shift ;;
    --target) TARGET_DIR="${2:-.}"; shift 2 ;;
    -h|--help)
      cat <<'EOF'
Usage: zsh qwen4_local_toolkit_macos27.zsh [options]
  --auto            Non-interactive mode for AI Agents
  --json            Emit sanitized JSON output
  --apply           Generate ~/.qwen4-local launchers & sampling presets
  --apply-ollama    Export Ollama FlashAttention + q4_0 KV cache into ~/.zshrc
  --scaffold-agent  Write .claude/agents/qwen4-local-worker.md in --target
  --target <dir>    Target workspace directory (default: .)
EOF
      exit 0
      ;;
    *) print -u2 -- "Unknown option: $1"; exit 1 ;;
  esac
done

# 1. Apple Silicon Unified Memory & Disk Detection (Sanitized)
ARCH="$(uname -m)"
MEM_BYTES="$(sysctl -n hw.memsize 2>/dev/null || echo 0)"
RAM_GB="$(awk -v b="$MEM_BYTES" 'BEGIN {printf "%.1f", b/1024/1024/1024}')"
CHIP_NAME="$(sysctl -n machdep.cpu.brand_string 2>/dev/null || echo 'Apple Silicon')"

mkdir -p "$TARGET_DIR" 2>/dev/null || true
FREE_DISK_KB="$(df -Pk "$TARGET_DIR" | awk 'NR==2 {print $4}')"
FREE_DISK_GB="$(awk -v k="${FREE_DISK_KB:-0}" 'BEGIN {printf "%.1f", k/1024/1024}')"

# Recommend GGUF or Dynamic MLX according to unified memory tier
TIER="Tier-D (12GB-Tight)"
REC_QUANT="UD-IQ2_XXS"
REC_MLX="none (use GGUF w/ SSD Engram)"
ACTIVE_GB="11.9"
DL_GB="23.4"
SMALL_QUANT_GUARD="true"

if awk -v r="$RAM_GB" 'BEGIN {exit !(r >= 48)}'; then
  TIER="Tier-A+ (48GB+ Unified)"
  REC_QUANT="UD-Q4_K_XL"
  REC_MLX="unsloth/Qwen4-35B-A3B-MLX-4bit"
  ACTIVE_GB="24.7"
  DL_GB="36.2"
  SMALL_QUANT_GUARD="false"
elif awk -v r="$RAM_GB" 'BEGIN {exit !(r >= 32)}'; then
  TIER="Tier-A (32GB Unified)"
  REC_QUANT="UD-Q4_K_XL"
  REC_MLX="unsloth/Qwen4-35B-A3B-MLX-4bit"
  ACTIVE_GB="24.7"
  DL_GB="36.2"
  SMALL_QUANT_GUARD="false"
elif awk -v r="$RAM_GB" 'BEGIN {exit !(r >= 22)}'; then
  TIER="Tier-B (24GB Unified)"
  REC_QUANT="UD-IQ4_XS"
  REC_MLX="none (use GGUF UD-IQ4_XS w/ SSD Engram)"
  ACTIVE_GB="20.5"
  DL_GB="32.0"
  SMALL_QUANT_GUARD="false"
elif awk -v r="$RAM_GB" 'BEGIN {exit !(r >= 16)}'; then
  TIER="Tier-C (16-18GB Unified)"
  REC_QUANT="UD-IQ3_XXS"
  REC_MLX="none (use GGUF UD-IQ3_XXS w/ SSD Engram)"
  ACTIVE_GB="17.2"
  DL_GB="28.7"
  SMALL_QUANT_GUARD="false"
fi

DISK_WARN="false"
if awk -v d="$FREE_DISK_GB" 'BEGIN {exit !(d < 45)}'; then
  DISK_WARN="true"
fi

# 2. Local Runtime & Trap Scan
LLAMA_FOUND="false"; command -v llama-server >/dev/null 2>&1 && LLAMA_FOUND="true"
OLLAMA_FOUND="false"; command -v ollama >/dev/null 2>&1 && OLLAMA_FOUND="true"
TIKTOKEN_FOUND="false"
MLX_LM_FOUND="false"
if command -v python3 >/dev/null 2>&1; then
  python3 -c "import tiktoken" >/dev/null 2>&1 && TIKTOKEN_FOUND="true"
  python3 -c "import mlx_lm" >/dev/null 2>&1 && MLX_LM_FOUND="true"
fi

OLLAMA_KV_BLOAT_TRAP="false"
if [[ "$OLLAMA_FOUND" == "true" ]]; then
  if [[ "${OLLAMA_FLASH_ATTENTION:-}" != "1" || -z "${OLLAMA_KV_CACHE_TYPE:-}" ]]; then
    OLLAMA_KV_BLOAT_TRAP="true"
  fi
fi

STALE_BASE_URL_TRAP="false"
if [[ -n "${OPENAI_BASE_URL:-}" && ! "${OPENAI_BASE_URL}" =~ localhost ]]; then
  STALE_BASE_URL_TRAP="true"
fi

# 3. Interactive Human Prompt
if (( AUTO == 0 )); then
  print -P "%B=== Qwen4-35B-A3B macOS 27 Local Triage ===%b"
  print -r -- "Unified Memory Tier: ${TIER} | GGUF: ${REC_QUANT} (${ACTIVE_GB} GB active)"
  print -r -- "Apple Silicon MLX:   ${REC_MLX} (avoid naive mlx_lm.convert 4-bit!)"
  if (( APPLY == 0 )); then
    read -r "ans_apply?Generate local Qwen4 launchers & presets in ~/.qwen4-local? [Y/n] "
    if [[ -z "$ans_apply" || "$ans_apply" == [Yy]* ]]; then APPLY=1; fi
  fi
  if [[ "$OLLAMA_FOUND" == "true" && $APPLY_OLLAMA -eq 0 ]]; then
    read -r "ans_ol?Append Ollama FlashAttention + q4_0 KV cache exports to ~/.zshrc? [y/N] "
    if [[ "$ans_ol" == [Yy]* ]]; then APPLY_OLLAMA=1; fi
  fi
  if (( SCAFFOLD_AGENT == 0 )); then
    read -r "ans_ag?Scaffold local Qwen4 worker profile in target directory? [y/N] "
    if [[ "$ans_ag" == [Yy]* ]]; then SCAFFOLD_AGENT=1; fi
  fi
fi

# 4. Apply Configs Safely
QWEN_DIR="${HOME}/.qwen4-local"
LAUNCHER_CREATED="false"
PRESETS_CREATED="false"
OLLAMA_ENV_APPLIED="false"
AGENT_SCAFFOLDED="false"
BACKUP_FILE="none"

if (( APPLY == 1 )); then
  mkdir -p "$QWEN_DIR"
  MIN_P="0.0"; [[ "$SMALL_QUANT_GUARD" == "true" ]] && MIN_P="0.01"

  THINK_ZSH="${QWEN_DIR}/launch-qwen4-thinking.zsh"
  FAST_ZSH="${QWEN_DIR}/launch-qwen4-fast.zsh"
  if [[ -f "$THINK_ZSH" ]]; then
    BACKUP_FILE="${THINK_ZSH}.bak.$(date +%Y%m%d%H%M%S)"
    cp "$THINK_ZSH" "$BACKUP_FILE"
  fi

  cat > "$THINK_ZSH" <<EOF
#!/usr/bin/env zsh
set -euo pipefail
exec llama-server -hf "unsloth/Qwen4-35B-A3B-GGUF:${REC_QUANT}" \\
  --host localhost --port 8081 \\
  --load-mode mmap --lazy-mode on -ot per_layer_token_embd=CPU \\
  --spec-type draft-mtp --spec-draft-n-max 2 \\
  -fa on -c 65536 \\
  --temp 1.0 --top-p 0.95 --top-k 20 --min-p ${MIN_P}
EOF

  cat > "$FAST_ZSH" <<EOF
#!/usr/bin/env zsh
set -euo pipefail
exec llama-server -hf "unsloth/Qwen4-35B-A3B-GGUF:${REC_QUANT}" \\
  --host localhost --port 8081 \\
  --load-mode mmap --lazy-mode on -ot per_layer_token_embd=CPU \\
  --spec-type draft-mtp --spec-draft-n-max 2 \\
  --reasoning off -fa on -c 65536 \\
  --temp 0.7 --top-p 0.80 --top-k 20 --min-p ${MIN_P} --presence-penalty 1.5
EOF
  chmod +x "$THINK_ZSH" "$FAST_ZSH"
  LAUNCHER_CREATED="true"

  cat > "${QWEN_DIR}/qwen4-sampling-presets.json" <<EOF
{
  "model": "unsloth/Qwen4-35B-A3B-GGUF:${REC_QUANT}",
  "mlx_model_recommended": "${REC_MLX}",
  "local_openai_base_url": "http://localhost:8081/v1",
  "thinking_mode": {
    "reasoning_effort": "high",
    "preserve_thinking": true,
    "temperature": 1.0,
    "top_p": 0.95,
    "top_k": 20,
    "min_p": ${MIN_P},
    "presence_penalty": 0.0,
    "repetition_penalty": 1.0
  },
  "non_thinking_mode": {
    "reasoning_effort": "off",
    "temperature": 0.7,
    "top_p": 0.80,
    "top_k": 20,
    "min_p": ${MIN_P},
    "presence_penalty": 1.5,
    "repetition_penalty": 1.0
  },
  "long_video_preprocessor": {
    "longest_edge": 469762048,
    "shortest_edge": 4096,
    "approx_video_tokens": 224000
  },
  "mtp_speculative": {
    "spec_type": "draft-mtp",
    "spec_draft_n_max": 2
  }
}
EOF
  PRESETS_CREATED="true"
fi

if (( APPLY_OLLAMA == 1 )); then
  ZSHRC="${HOME}/.zshrc"
  touch "$ZSHRC"
  if ! grep -q "OLLAMA_KV_CACHE_TYPE" "$ZSHRC" 2>/dev/null; then
    cat >> "$ZSHRC" <<'EOF'

# Qwen4-35B-A3B Ollama KV & FlashAttention Guard
export OLLAMA_FLASH_ATTENTION=1
export OLLAMA_KV_CACHE_TYPE=q4_0
export LLAMA_ARG_MOE_CACHE_MIB=4096
EOF
  fi
  OLLAMA_ENV_APPLIED="true"
fi

if (( SCAFFOLD_AGENT == 1 )); then
  mkdir -p "${TARGET_DIR}/.claude/agents"
  cat > "${TARGET_DIR}/.claude/agents/qwen4-local-worker.md" <<'EOF'
---
name: qwen4-local-worker
description: Local Qwen4-35B-A3B worker routed to localhost:8081 with Engram SSD offload and MTP depth=2.
---
Use local OpenAI-compatible endpoint http://localhost:8081/v1 (model: Qwen4-35B-A3B).
Keep reasoning_effort=low for quick file reads and high for architecture or multi-file refactors.
EOF
  AGENT_SCAFFOLDED="true"
fi

if (( JSON_MODE == 1 )); then
  cat <<EOF
{
  "platform": "macOS 27",
  "arch": "${ARCH}",
  "chip": "${CHIP_NAME}",
  "unified_ram_gb": ${RAM_GB},
  "free_disk_gb": ${FREE_DISK_GB},
  "recommended_tier": "${TIER}",
  "recommended_gguf_quant": "${REC_QUANT}",
  "recommended_mlx_repo": "${REC_MLX}",
  "active_footprint_gb": ${ACTIVE_GB},
  "download_size_gb": ${DL_GB},
  "llama_server_found": ${LLAMA_FOUND},
  "ollama_found": ${OLLAMA_FOUND},
  "tiktoken_installed": ${TIKTOKEN_FOUND},
  "mlx_lm_installed": ${MLX_LM_FOUND},
  "disk_space_warning": ${DISK_WARN},
  "ollama_kv_bloat_trap": ${OLLAMA_KV_BLOAT_TRAP},
  "stale_base_url_trap": ${STALE_BASE_URL_TRAP},
  "small_quant_anti_loop_needed": ${SMALL_QUANT_GUARD},
  "launcher_created": ${LAUNCHER_CREATED},
  "presets_created": ${PRESETS_CREATED},
  "ollama_env_applied": ${OLLAMA_ENV_APPLIED},
  "agent_scaffolded": ${AGENT_SCAFFOLDED},
  "backup_file": "${BACKUP_FILE}"
}
EOF
else
  print -r -- ""
  print -P "%B=== Qwen4-35B-A3B Diagnostic Summary (macOS 27 · Sanitized) ===%b"
  print -r -- "Chip / Unified RAM:      ${CHIP_NAME} (${ARCH}) | ${RAM_GB} GB"
  print -r -- "Free Disk on Target:     ${FREE_DISK_GB} GB (warning=${DISK_WARN})"
  print -r -- "Tier / GGUF / MLX:       ${TIER} -> ${REC_QUANT} | MLX: ${REC_MLX}"
  print -r -- "Runtimes:                llama-server=${LLAMA_FOUND} | ollama=${OLLAMA_FOUND} | tiktoken=${TIKTOKEN_FOUND} | mlx_lm=${MLX_LM_FOUND}"
  print -r -- "Traps:                   OllamaKVBloat=${OLLAMA_KV_BLOAT_TRAP} | StaleBaseURL=${STALE_BASE_URL_TRAP} | AntiLoopGuard=${SMALL_QUANT_GUARD}"
  print -r -- "Applied:                 launchers=${LAUNCHER_CREATED} | presets=${PRESETS_CREATED} | ollamaEnv=${OLLAMA_ENV_APPLIED} | agent=${AGENT_SCAFFOLDED}"
fi

Human interactive run:

chmod +x ./qwen4_local_toolkit_macos27.zsh && zsh ./qwen4_local_toolkit_macos27.zsh

5.2 Method 2: AI Agent Full Auto-Config (Copy-Paste Prompt)

Using Claude Code, MiniMax Code, Codex, or Antigravity? Save your OS script into the workspace and paste this prompt to let your Agent run diagnostics, generate launchers, and verify every flag automatically:

Run the zero-dependency Qwen4-35B-A3B local diagnostic and setup script for the current OS:
- Windows 11: powershell -ExecutionPolicy Bypass -File .\qwen4_local_toolkit_windows11.ps1 -Auto -Json -Apply -ApplyOllama -ScaffoldAgent -Target .
- Ubuntu 26.04: bash ./qwen4_local_toolkit_ubuntu2604.sh --auto --json --apply --apply-ollama --scaffold-agent --target .
- macOS 27: zsh ./qwen4_local_toolkit_macos27.zsh --auto --json --apply --apply-ollama --scaffold-agent --target .

After execution, verify all 5 checkpoints:
1. Confirm disk_space_warning is false (target drive has enough room for the GGUF/MLX weights + 20.5B Engram);
2. Report recommended_tier and recommended_quant (plus recommended_mlx_repo on 32GB+ macOS, warning against naive mlx_lm.convert 4-bit);
3. Check ollama_kv_bloat_trap and stale_base_url_trap, and provide activation commands if ~/.qwen4-local/ollama-override.conf or ~/.zshrc was updated;
4. Verify ~/.qwen4-local/launch-qwen4-thinking.*, launch-qwen4-fast.*, and qwen4-sampling-presets.json exist with mmap Engram CPU/SSD offload and --spec-draft-n-max 2;
5. Verify .claude/agents/qwen4-local-worker.md is scaffolded in the workspace targeting http://localhost:8081/v1.

6. FAQ: 7 Practical Questions Before You Deploy Tomorrow

Q1: Can a 16GB or 18GB laptop really run a 56.8B-tensor model smoothly?

Yes—thanks to SSD Engram offloading paired with Unsloth Dynamic 3-bit quants. Pulling UD-IQ3_XXS (17.2 GB active) or UD-Q3_K_XL (19.4 GB active) with --load-mode mmap --lazy-mode on -ot per_layer_token_embd=CPU keeps the 20.5B N-gram table on NVMe storage. Unsloth's 300-question benchmark shows UD-IQ3_XXS still retains 94.8% accuracy (within 0.5 points of full BF16).

Q2: Why does my local engine complain that qwen4_moe is unknown?

Qwen4 combines Gated DeltaNet, Qwen Sparse Attention, and Layer-2 PLE—none of which exist in older binaries. Update llama.cpp past PR #33626, upgrade transformers to 5.26+ with pip install tiktoken, or pull the latest Day-0 releases of vLLM and SGLang.

Q3: Should I use ollama run qwen4 or custom llama-server flags?

ollama run qwen4 (and ollama launch claude --model qwen4) is unbeatable for 10-second convenience, provided you enable OLLAMA_FLASH_ATTENTION=1 and OLLAMA_KV_CACHE_TYPE=q4_0 to stop long-context KV bloat. If you are on a 24GB GPU or 16–24GB Mac and want maximum speed via --moe-cache-mib, explicit Engram SSD offloading, or custom --ple swaps, running llama-server directly is noticeably faster.

Q4: Can I mix a 4-bit MoE backbone with an 8-bit Engram dictionary?

Yes! Because Unsloth isolates the Engram table in its own shard and publishes standalone precision variants inside the engram/ directory, pairing UD-Q4_K_XL with Qwen4-35B-A3B-engram-Q8_0 via --ple cuts Mean KLD by roughly 6% while barely touching GPU VRAM.

Q5: Which reasoning_effort level (xhigh / high / low / off) saves the most time?

Be careful with low on multi-step coding agents: Qwen's model card explicitly warns that under-thinking often triggers failed tool calls and retries, increasing total wall-clock time. Keep high (default) for daily coding, drop to off (with temp=0.7, presence_penalty=1.5) for quick prose/translation, and escalate to xhigh for tricky multi-file refactors.

Q6: What is the best cloud API option when my local rig is tied up?

Official Qwen Cloud (qwen4-35b-a3b) or OpenRouter (qwen/qwen4-35b-a3b), where providers currently serve it at $0.04 / 1M input, $0.30 / 1M output, and $0.003 / 1M cache read with 0.26–0.59s P50 latency and up to 278 tok/s throughput.

Q7: Will hour-long video inputs blow up VRAM?

The 27-layer ViT merges 2×2 spatial patches and pairs frames at 2fps, while Gated DeltaNet keeps sequence state bounded. Just remember to override video_preprocessor_config.json's longest_edge to 469762048 (~224K video tokens) for long footage—or pass --media-io-kwargs '{"video": {"num_frames": -1}}' in vLLM and tune fps per request.


References & Primary Sources

Comments

Sign in with GitHub to comment. Chinese and English versions share the same discussion. Discuss on GitHub

Views --