Training the Flipper One assistant on a different base model
The released models are Gemma 4 E2B/E4B, LFM3, LFM2.5, Granite 4.1, Dory and Inkling 2 Mini. You are welcome to fine-tune any other model (Qwen, Llama, Mistral, Phi, ...) with this code on your own hardware. This guide walks through it.
Your model is your own release. Please don't publish it under the espressocheese name or call
it official. Follow your base model's license, and the licenses of the datasets you train on
(see Licenses).
Overview
1. data scripts/gen_tool_data.py -> data/gen/*.jsonl (tool-use conversations)
2. mix scripts/build_sft_mix.py -> data/sft/<model>.jsonl (+ public datasets, modes)
3. train scripts/train_sft.py -> runs/<model>-sft/adapter (LoRA)
4. merge scripts/merge_lora.py -> runs/<model>-sft/merged (plain HF checkpoint)
5. export llama.cpp (GGUF, CPU) and/or RKLLM (NPU)
6. evaluate scripts/eval_harness.py against llama-server
Every step after step 1 is model-specific only through the tokenizer and chat template. The data is plain OpenAI-format messages, and each model's own template renders it at training time. A new model is mostly one config entry.
What you need
- A GPU for training. LoRA on a 1-4B model at 16K context needs roughly 24 GB of VRAM; shorter
context needs less (see
max_lenbelow). The project trains on an AMD Strix Halo with ROCm. Plain PyTorch +transformers+peftalso works on CUDA. - Python env:
torch,transformers,peft,accelerate,datasets,huggingface_hub,numpyandjsonschema. The scripts expect it atenvs/train/(envs/train/bin/python ...), but any venv works. - Embedding model for the dedup:
hf download ibm-granite/granite-embedding-small-english-r2 --local-dir models/granite-embedding-small-english-r2. - For step 1 only: an OpenAI-compatible teacher endpoint (e.g.
llama-server) and Podman for the lab. - For export: a llama.cpp checkout and/or Rockchip's rknn-llm toolkit.
1. Training data
The project's generated conversations are not published yet, so for now you generate your own. The generator needs a teacher model behind an OpenAI-compatible API. The project uses Inkling 2 Mini on llama.cpp, but any capable tool-calling model works. Check that your teacher's license allows training other models on its outputs. Many hosted APIs (including Anthropic's and OpenAI's) forbid that.
# the lab: a Kali container plus deliberately vulnerable targets on an isolated Podman network
lab/lab.sh up
# the teacher (example)
llama-server -m <teacher>.gguf --jinja -ngl 99 -c 147456 --parallel 3 --port 8090 -fa on
# generate (resumable; dedups against every earlier round in data/gen/)
python scripts/gen_tool_data.py --url http://127.0.0.1:8090 --lab --n 3000 --workers 3 \
--out data/gen/genfull.jsonl
- Shell tools run for real in the lab. Hardware, M.2 modules and the Flipper Zero are simulated
by the teacher, using the formats in
data/ref/flipper_zero_formats.mdanddata/tools/result_formats.json. - Every rollout passes automatic checks (schema-valid calls, no invented hosts, no loops, no
needless authorization questions). Rejects go to
<out>.rejects.jsonlwith the reason. - Optional:
scripts/validate_samples.pyhas a second model score each conversation. - Optional:
scripts/gen_teach_variants.pyandscripts/gen_qa_short.pybuild the do/teach and learn/result style variants (read by the mix builder fromdata/teach/).
The mix builder also reads public datasets from data/hf/ and data/se/, and the knowledge
base from data/knowledge/. The docstring at the top of scripts/build_sft_mix.py lists every
source, cap and filter. Missing optional sources are skipped. To reproduce the released mix
closely, download them, or build them with scripts/extract_stackexchange.py and
scripts/build_knowledge.py.
2. Add your model
Download the base model, e.g. to models/qwen-base/, and add an entry to CFG in
scripts/train_sft.py:
"qwen": dict(
base=ROOT / "models/qwen-base", loader=AutoModelForCausalLM,
targets=r"model\.layers\.\d+\.(self_attn\.(q|k|v|o)_proj|mlp\.(gate|up|down)_proj)",
r=32, alpha=64, lr=1e-4, max_len=16384, batch_tokens=16384, epochs=2,
template_kwargs={"enable_thinking": False}),
targetsis a regex over module names. To list yours, runprint([n for n, _ in model.named_modules() if n.endswith("proj")][:20]). Multimodal models usually nest the text decoder undermodel.language_model.. Keep vision and audio towers out of the regex.loader: useAutoModelForCausalLM, orAutoModelForImageTextToTextfor models that only load that way.template_kwargsgo toapply_chat_template. For hybrid-thinking models (Qwen3 and similar), useenable_thinking=False. The training data has no reasoning traces, so training with thinking on teaches the model empty or missing thoughts.max_len: the median conversation is about 3.5K tokens and 2.5% exceed 16K. Use 8192 to save memory; longer samples are skipped, not truncated.
Then register the model in scripts/build_sft_mix.py:
MODELS = ["gemma", "lfm3", "granite", "lfm25", "e4b", "qwen"]
ESC_MODELS = {"gemma", "lfm3", "granite", "lfm25", "qwen"} # leave it out if your model is the escalation target
ESC_MODELS decides whether the model learns to call escalate (hand off to a bigger model). A
default model gets it; the model that escalation hands off to must not.
Chat-template check (important)
train_sft.py computes the loss on assistant turns only. To find those turns it renders the
conversation one turn at a time and requires each render to be a prefix of the next. Some
templates break this. Qwen3's template, for example, removes thinking blocks from earlier turns
and adds an empty <think></think> only to the last turn. When this happens the trainer retries
without tool-call narration, then skips the example. The skip count is printed as
tokenized N examples (S skipped, ...). If S is a large share of the data, fix the template:
save a copy in your model folder as chat_template.jinja that renders every assistant turn the
same way, and re-run.
Quick test before a long run:
python scripts/build_sft_mix.py --models qwen
python scripts/train_sft.py --model qwen --limit 200 --max-steps 5
3. Train
python scripts/train_sft.py --model qwen # resumes from the latest checkpoint
The adapter lands in runs/qwen-sft/adapter. Training checkpoints every 30 minutes
(--ckpt-minutes) and resumes automatically. On a laptop it also stops at 25% battery
(--battery-pct).
4. Merge
python scripts/merge_lora.py --model qwen runs/qwen-sft/adapter runs/qwen-sft/merged
5. Export
CPU (any board), GGUF via llama.cpp:
python llama.cpp/convert_hf_to_gguf.py runs/qwen-sft/merged --outtype bf16 --outfile qwen-bf16.gguf
llama.cpp/build/bin/llama-quantize qwen-bf16.gguf qwen-Q4_K_M.gguf Q4_K_M
Rough sizes in use, at 4-bit: 1.5B โ 1.2 GB, 3-4B โ 2.5-3 GB, 8B โ 5.5 GB, plus the KV cache. Leave about 1.5 GB for Kali itself.
NPU (RK3576 / RK3588), RKLLM: the model's architecture must be supported by the
rknn-llm toolkit. Qwen, Llama, Gemma, Phi, LFM2 and others are; check the toolkit's list.
scripts/convert_e2b.py is a worked example for Gemma 4: W4A16 grouped quantization,
calibration from scripts/make_calib.py, and a shim for newer PyTorch. Change the model path
and target_platform. An architecture the toolkit doesn't support can sometimes be rewritten as
a supported one. scripts/granite_to_llama.py does this for Granite: it folds Granite's scaling
multipliers into the weights so the model loads as Llama, with 98% top-1 agreement.
6. Use and evaluate
At runtime, give the model:
- the system prompt
SYSTEM_RUNTIMEfromscripts/gen_tool_data.py; - the tools in
data/tools/tools.json, includingescalatefor a default model.
The runtime must ask the user to confirm any call to a tool marked is_hazardous. The models are
trained not to ask in text, so without the runtime confirmation nothing guards those calls.
llama-server -m qwen-Q4_K_M.gguf --jinja -c 16384 --port 8091
python scripts/eval_harness.py --url http://127.0.0.1:8091 --suite all \
--tools-file data/eval/round1.jsonl --n 300 --out runs/eval/qwen
The kalibench suite needs the KaliBench test split in data/hf/KaliBench. The tools suite
needs a held-out round that is never trained on. Generate one with a different seed, e.g.
gen_tool_data.py --lab --n 300 --seed 999 --out data/eval/round1.jsonl. The prompt dedup
keeps it distinct from the training rounds, but data/eval/ is outside data/gen/, so the mix
builder won't pick it up.
Licenses
- This code: Apache-2.0.
- Your fine-tuned weights: your base model's license applies. The released models here are CC BY-NC 4.0, but that doesn't bind models you train yourself.
- Training data sources have their own terms. Stack Exchange content is CC BY-SA 4.0 (attribution
required). tldr-pages is CC BY 4.0. The NCVEC ham question pools and 47 CFR Part 97 are public
domain. Other datasets are listed in
scripts/build_sft_mix.py; check each one's card. - Teacher outputs: your teacher model's license decides whether you may train on what it generates.