These schematics were converted into instruction→output training pairs (schematic generation, section understanding, component reference lookup) using Gemma 4 E4B-it running locally.
Synthetically Generated Pairs
Generated using Gemma 4 E4B-it (via LM Studio) as a teacher model, covering:
After training, LoRA adapters were merged into the base model weights at bf16 precision and exported to GGUF Q8_0 format via a patched convert_hf_to_gguf.py.
GGUF Compatibility Note
Gemma 4 E2B uses a shared-KV mechanism where layers 15–34 reuse the key/value projections from layers 13 (SWA) and 14 (global). Standard GGUF converters omit these tensors via PyTorch parameter deduplication.
The GGUF file in this repo includes explicit copies of the shared KV tensors for all 35 layers (SWA layers → blk.13 weights, global layers → blk.14 weights), ensuring compatibility with all llama.cpp-based runtimes including LM Studio and Ollama.
Additionally, this file has been patched to correct two issues present in the raw export — see the Technical Notes section below for full details.
Quick Usage
Ollama
bash
1# 1. Save a Modelfile2cat> Modelfile <<'EOF'
3FROM KiCad-Gemma4-E2B-v3-Q8_0.gguf
45TEMPLATE """<bos><start_of_turn>user
6{{ .Prompt }}<end_of_turn>
7<start_of_turn>model
8{{ .Response }}<end_of_turn>
9"""
1011PARAMETER stop "<end_of_turn>"
12PARAMETER stop "<start_of_turn>"
13PARAMETER temperature 0.2
14PARAMETER num_ctx 8192
15EOF1617# 2. Create the model18ollama create kicad-gemma4-v3 -f Modelfile
⚠️ Important: Use the /api/chat endpoint with "think": false. Ollama 0.20.x automatically enables Gemma 4 thinking mode which produces empty responses via /api/generate. See Technical Notes below.
python
1import requests
23r = requests.post("http://localhost:11434/api/chat", json={4"model":"kicad-gemma4-v3",5"messages":[{"role":"user","content":"What does DRC stand for in KiCad?"}],6"think":False,7"stream":False8})9print(r.json()["message"]["content"])
LM Studio
Download KiCad-Gemma4-E2B-v3-Q8_0.gguf
Place it at: .lmstudio/models/CanadaDiver/KiCad-Gemma4-E2B-v3/KiCad-Gemma4-E2B-v3-Q8_0.gguf
Select Gemma as the chat template and load — no extra configuration required
Recommended Companion App
For reliable schematic generation in LM Studio, use the companion app:
The companion app connects to LM Studio's local API, requests a structured circuit plan from the model, converts that plan into a real KiCad schematic with deterministic Python code, and validates the generated file. Direct raw .kicad_sch generation from plain chat is not the recommended production workflow.
1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
34model_id ="CanadaDiver/KiCad-Gemma4-E2B-v3"5tokenizer = AutoTokenizer.from_pretrained(model_id)6model = AutoModelForCausalLM.from_pretrained(7 model_id,8 torch_dtype=torch.bfloat16,9 device_map="auto"10)1112messages =[{"role":"user","content":"Write a KiCad schematic for a 3.3V LDO using LP2985."}]13inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)14outputs = model.generate(inputs, max_new_tokens=1024, temperature=1.0, top_k=64, top_p=0.95)15print(tokenizer.decode(outputs[0][inputs.shape[-1]:], skip_special_tokens=True))
Agentic Use — KiCad MCP Server
Pair this model with the companion mcp-kicad-sch-api MCP server to give it live read/write access to real .kicad_sch files. The model generates schematic intent; the MCP server executes it against an actual KiCad file on disk.
Install
pip install mcp-kicad-sch-api
Requires Python 3.10+ and KiCad installed (for symbol libraries).
Configure — Claude Desktop
Add to %APPDATA%\Claude\claude_desktop_config.json (Windows) or ~/Library/Application Support/Claude/claude_desktop_config.json (macOS):
claude mcp add kicad-sch -- python -m mcp_kicad_sch_api
Available MCP Tools
Tool
Description
create_schematic
Create a new .kicad_sch file
load_schematic
Load an existing schematic from disk
save_schematic
Save the current schematic to disk
add_component
Place a component (lib_id, reference, value, position, footprint)
search_components
Search KiCad symbol libraries by keyword
add_wire
Draw a wire between two coordinates
add_label
Add a net label at a position
add_hierarchical_label
Add a hierarchical interface label
add_junction
Add a junction dot at a wire crossing
list_components
List all components in the open schematic
get_schematic_info
Get component count, wire count, and file info
get_component_pin_position
Get the absolute XY position of a specific pin
add_label_to_pin
Attach a net label directly to a component pin
connect_pins_with_labels
Connect two pins via a shared net name
list_component_pins
List all pins for a component with their positions
remove_component
Remove a component by reference
remove_wire
Remove a wire by UUID
Example Agentic Workflow
With the MCP server running alongside this model in Claude Desktop or Claude Code:
"Create a 3.3 V LDO regulator schematic using the LP2985. Add input and output bypass caps. Save it as ldo_3v3.kicad_sch."
The model will call create_schematic, add_component (×3), add_wire (multiple), add_label, and save_schematic in sequence — producing a valid KiCad 8 schematic file without manual placement.
Hardware & Performance
Tested on RTX 5080 (16 GB VRAM) with ~11 GB already in use:
Runtime
GPU layers
Speed
Ollama 0.20.7
22–34 / 36 (split offload)
~19–40 tok/s
LM Studio 0.4.11
full GPU
~40+ tok/s
Technical Notes — Bugs Encountered & How They Were Fixed
Getting this GGUF to run correctly under Ollama and LM Studio required resolving three separate bugs, all rooted in how Gemma 4's mixed-architecture interacts with different inference runtimes. Documented here so others do not have to rediscover them.
Bug 1 — Double BOS Token → Empty Output (Ollama)
Symptom: Model loaded cleanly, generated the correct token count at normal speed, but response was always an empty string. eval_count was non-zero, done_reason was stop or length. No error shown.
Root cause: The GGUF metadata field tokenizer.ggml.add_bos_token was set to true. Ollama's tokenizer honoured this and prepended a BOS token (<bos>, ID 2) to every prompt. The Modelfile template also began with <bos>, so the model received a double BOS at position 0. Gemma 4 interprets a double BOS as a malformed sequence and outputs only non-printable special tokens — decoded text is empty.
How it was found: Context token IDs were decoded against the GGUF vocabulary. The first two prompt tokens were both <bos> (ID 2). Ollama logs showed: vocabulary.go:49 warning: adding bos token to prompt which already has it.
Fix: Binary patch of the GGUF — located the tokenizer.ggml.add_bos_token key/value pair (search pattern: uint64-LE string length + key bytes + type code 0x07 for BOOL + value byte 0x01), changed the value byte from 0x01 (true) to 0x00 (false). Ollama no longer prepends BOS automatically; the template's explicit <bos> is the only one present.
Symptom: Even after fixing Bug 1, template-mode inference still produced an empty response. Raw-mode inference ("raw": true with a fully-formatted prompt) worked correctly and produced fluent answers.
Root cause: Ollama 0.20.x automatically assigns RENDERER gemma4 and PARSER gemma4 to any model whose GGUF architecture is gemma4. The Gemma 4 renderer unconditionally injects a hidden system turn containing the special <|think|> token (ID 98) before the first user turn — regardless of any custom TEMPLATE directive in the Modelfile. This token puts Gemma 4 into chain-of-thought thinking mode. Thinking tokens are filtered from the response field, so with a typical num_predict budget the model never exits the thinking phase and the response is empty.
How it was found: Context token IDs were decoded using the GGUF vocabulary. The decoded prompt sequence was:
<bos> <start_of_turn> system \n <|think|> \n <end_of_turn> \n <start_of_turn> user \n [actual prompt] ...
This hidden system turn was absent in raw mode. The generated tokens decoded to <|channel|> thought \n Thinking Process ... — internal reasoning tokens with no visible text equivalent.
Fix: Use the /api/chat endpoint with "think": false at the request level. The think parameter is not accepted as a Modelfile PARAMETER in Ollama 0.20.x — it must be passed per request. With think: false the system turn is suppressed, prompt token count drops from 31 to 24, and the model responds correctly.
Root cause: Gemma 4 E2B uses mixed local/global attention. Local (sliding-window) layers have KV head dimension 256; global layers have 512. llama.cpp places global layers at 0-indexed positions 4, 9, 14, 19, 24, 29, 34. The original GGUF was exported with 1-indexed block names (blk.1–blk.35), placing global layers at blk.5, blk.10, blk.15, etc. When llama.cpp read blk.15 it mapped it to 0-indexed layer 15 (a local layer, expecting 256), but found a global-layer tensor (512 + two extra singleton dimensions). This is also why Ollama could load the file — its bundled llama.cpp version did not perform the same strict tensor dimension check.
How it was found: LM Studio server logs at ~/.lmstudio/server-logs/ contained the exact tensor name and expected vs. actual shapes. Cross-referencing with the n_embd_k_gqa array printed at load time confirmed the global/local pattern mismatch.
Fix: The GGUF in this repo was produced by the KV-layer injection pipeline which, as a side effect, re-indexed all block tensors from 1-based to 0-based naming (blk.1→blk.0, …, blk.35→blk.34) and reshaped the global-layer KV tensors to the correct 2D form. The resulting file has blk.0–blk.34 with global layers correctly at 0-indexed positions 4, 9, 14, 19, 24, 29, 34 and all tensor shapes matching llama.cpp's expectations. Both Ollama and LM Studio load this file without errors.
Limitations
Optimized for KiCad tasks; general reasoning capability is reduced vs. the base model
Always run KiCad DRC before sending any generated schematic to fabrication
Trained primarily on KiCad 8.x conventions; KiCad 9.x/10.x syntax may differ in places
Not a substitute for professional electrical engineering review