Or: what I’ve learned so far fine-tuning on my own Claude Code session logs, including the parts I got wrong.
Up front: this is a hobby project. I’m not a researcher, this isn’t a paper, and nothing here is a benchmark result. I bought a Spark, got curious about whether I could teach a local model to work the way my coding agent does, and have been learning by breaking things ever since. Most of what follows is me writing down mistakes so the next person doesn’t have to make them.
That said — a few of those mistakes were expensive enough to be worth sharing. One was a missing package worth a 2.52× throughput win that I ran without for a month. And the data recipe seems genuinely underused: turning your own agentic coding sessions into supervised fine-tuning data.
If you’re an actual ML person reading this, some of my choices will look naive. Please tell me. That’s half of why I’m posting.
This is a long post. Skim the headings.
What the system does
Fine-tune Qwen3.6-35B-A3B (MoE, 35B total / 3B active) into a coding agent via QLoRA, and serve the resulting adapter on top of the NVFP4 quantization of the same model. The box does both jobs on a schedule:
17:00 Mon–Fri stop the server → train until the deadline → publish adapter → restart server
05:00 daily safety net: make sure the server is back up
Training is time-boxed, not run-to-completion. It gets killed at 04:30 and resumes from its last checkpoint the next night. A kill (rc=124) is the normal exit path, not a failure.
Hardware: 1× DGX Spark (GB10), 121 GB unified memory, compute capability 12.1 (sm_121a), driver 580.159.03, nvcc 13.0. Training venv: torch 2.10.0+cu128, transformers 5.5.0, triton 3.6.0, unsloth 2026.6.9, flash-linear-attention 0.5.1. Serving: vLLM in Docker.
The central design decision: train bf16, serve NVFP4
You cannot fine-tune the NVFP4 checkpoint. NVFP4 (compressed-tensors / nvfp4-pack-quantized) is a post-training quantization format with no gradient path. The obvious workaround — train, merge, re-quantize nightly — would cost hours and hundreds of GB of scratch every single night.
So instead:
- train against the bf16 base
- serve the NVFP4 base with
--enable-lora, hot-attaching the night’s adapter
Attaching an adapter takes seconds and costs a ~27 MB file per night. vLLM reports “MoE model detected. Using fused MoE LoRA implementation” and happily serves both names side by side:
Qwen3.6-35B-A3B-NVFP4— the baseQwen3.6-35B-A3B-Coder-NVFP4— base + adapter
Serving both simultaneously is what makes A/B evaluation cheap, and you’ll want that, because the adapter is trained against bf16 weights and applied over NVFP4 ones. That mismatch is standard practice but it was an untested assumption in my setup for weeks. I’ve now measured it (see the evaluation section) and it holds up — but measure it yourself rather than inheriting my result.
One deployment detail that cost me time: adapters must live under a path the container actually mounts. In my case the container maps ~/.cache/vllm → /root/.cache/vllm, so anything sitting in the training project directory is simply invisible inside the container. The publish step copies the checkpoint’s adapter into the mounted directory and repoints a current symlink.
Where the training data comes from: your own Claude Code sessions
This is the part I’d most like other people to steal.
Claude Code writes a complete JSONL transcript of every session to ~/.claude/projects/**/*.jsonl. Every user turn, every assistant turn including thinking blocks and tool calls, every tool result. If you’ve been using an agentic coding tool for months, you are sitting on tens of thousands of examples of an agent doing your kind of work, with your toolset, in your codebases — which is exactly the distribution you want a local model to match.
My final dataset is 80,659 examples, of which 76,010 come from these session logs. The remainder are purpose-built agent traces.
The parser
Each assistant turn that contains a tool call or a final text answer becomes one training example: the flattened transcript so far is the context (masked, no loss), and the assistant’s actual output is the completion (trained).
#!/usr/bin/env python3
"""Parse local Claude Code session logs (~/.claude/projects/**/*.jsonl) into
Axolotl input_output JSONL.
Each assistant turn that contains a tool_use or a final text answer becomes one
training example: context = flattened transcript so far (masked),
completion = <think>{thinking}</think> + tool_call(s) / text (trained).
"""
import glob
import json
import os
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "data", "cc_train.jsonl")
PROJECTS = os.path.expanduser("~/.claude/projects")
EOS = "<|im_end|>"
MAX_CTX_CHARS = 24000 # keep transcript bounded; keep the most recent tail
def _render_value(v):
return v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)
def render_tool_call(name, inp):
parts = [f"<tool_call>\n<function={name}>\n"]
if isinstance(inp, dict):
for k, v in inp.items():
parts.append(f"<parameter={k}>\n{_render_value(v)}\n</parameter>\n")
parts.append("</function>\n</tool_call>")
return "".join(parts)
def text_of(content):
"""Extract plain text from a message.content (str or list of blocks)."""
if isinstance(content, str):
return content
if isinstance(content, list):
out = []
for b in content:
if isinstance(b, dict) and b.get("type") == "text":
out.append(b.get("text") or "")
return "\n".join(out)
return ""
def is_tool_result(msg):
c = msg.get("content")
return isinstance(c, list) and any(
isinstance(b, dict) and b.get("type") == "tool_result" for b in c
)
def tool_result_text(content):
out = []
for b in content:
if isinstance(b, dict) and b.get("type") == "tool_result":
r = b.get("content")
out.append(text_of(r) if not isinstance(r, str) else r)
return "\n".join(out)[:2000]
def build_completion(blocks):
"""blocks = assistant message.content list. Returns completion str or None."""
thinking = "\n".join(
b.get("thinking") or "" for b in blocks
if isinstance(b, dict) and b.get("type") == "thinking"
).strip()
texts = [b.get("text") or "" for b in blocks
if isinstance(b, dict) and b.get("type") == "text"]
tools = [(b.get("name"), b.get("input") or {}) for b in blocks
if isinstance(b, dict) and b.get("type") == "tool_use"]
think = f"<think>\n{thinking}\n</think>\n\n"
if tools:
body = ""
pre = "\n".join(t for t in texts if t.strip()).strip()
if pre:
body += pre + "\n\n"
body += "\n".join(render_tool_call(n, i) for n, i in tools)
return think + body + EOS
text = "\n".join(t for t in texts if t.strip()).strip()
if text:
return think + text + EOS
return None
def process_file(path, out):
n = 0
transcript = [] # list of strings
try:
objs = [json.loads(l) for l in open(path) if l.strip()]
except Exception:
return 0
for o in objs:
if o.get("isMeta"):
continue
t = o.get("type")
msg = o.get("message")
if not isinstance(msg, dict):
continue
if t == "user":
if is_tool_result(msg):
transcript.append("TOOL_RESULT: " + tool_result_text(msg["content"]))
else:
txt = text_of(msg.get("content")).strip()
if txt:
transcript.append("USER: " + txt)
elif t == "assistant":
blocks = msg.get("content")
if not isinstance(blocks, list):
continue
comp = build_completion(blocks)
if comp:
ctx = "\n".join(transcript).strip()[-MAX_CTX_CHARS:]
if ctx:
out.write(json.dumps({"segments": [
{"label": False, "text": ctx},
{"label": True, "text": comp},
]}, ensure_ascii=False) + "\n")
n += 1
# append a compact form of this assistant turn to the transcript
txt = text_of(blocks).strip()
tools = [b.get("name") for b in blocks
if isinstance(b, dict) and b.get("type") == "tool_use"]
line = "ASSISTANT: " + txt
if tools:
line += f" [called: {', '.join(tools)}]"
transcript.append(line.strip())
return n
def main():
files = sorted(glob.glob(os.path.join(PROJECTS, "**", "*.jsonl"), recursive=True))
print(f"found {len(files)} session files")
total = 0
with open(OUT, "w") as out:
for f in files:
c = process_file(f, out)
total += c
print(f"wrote {total} examples -> {OUT}")
if __name__ == "__main__":
main()
A few notes on the choices in there:
Tool results go back into the context as TOOL_RESULT: lines, truncated to 2000 chars. Tool output is model input, not something you want the model learning to generate. Truncating it hard also stops one cat of a large file from eating your whole context budget.
Assistant turns are compacted before re-entering the transcript — the text plus a [called: Read, Grep] marker rather than the full tool-call XML. It keeps the running context readable and short.
Thinking blocks are preserved in the completion. That’s a large part of the point: you’re training the reasoning-then-act pattern, not just the final tool call.
Export early and often — the logs rotate
This is the single most important operational warning in this post. ~/.claude/projects gets pruned. I have two exports, one from June and one from July. They overlap by only about 6%. The June export covers sessions that no longer exist on disk and cannot be regenerated — roughly 45,000 examples that would simply be gone if I hadn’t run the parser that month.
Run the extractor on a cron and keep the outputs. Dedupe at build time on a hash of context + completion:
seen, deduped = set(), []
for o in all_rows:
k = hash(o["segments"][0]["text"] + "\x00" + o["segments"][1]["text"])
if k in seen:
continue
seen.add(k)
deduped.append(o)
Scrub secrets before anything else touches the data
Your session logs contain whatever was on your screen: API keys pasted into a terminal, tokens in env dumps, private keys in a misdirected cat. Regex the obvious families and replace them before the data is ever tokenized, shuffled, or copied to a backup share:
PAT = {
"anthropic": re.compile(r"sk-ant-[A-Za-z0-9_\-]{20,}"),
"openai": re.compile(r"sk-(?!ant-)[A-Za-z0-9]{20,}"),
"hf": re.compile(r"hf_[A-Za-z0-9]{30,}"),
"github": re.compile(r"\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{30,}\b|github_pat_[A-Za-z0-9_]{30,}"),
"aws": re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
"slack": re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}"),
"google": re.compile(r"\bAIza[0-9A-Za-z_\-]{35}\b"),
"privkey": re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----[\s\S]+?-----END (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----"),
"bearer": re.compile(r"(?i)\b(?:bearer|authorization:?)\s+[A-Za-z0-9._\-]{20,}"),
"kv": re.compile(r"(?i)\b(api[_-]?key|secret[_-]?key|secret|access[_-]?token|auth[_-]?token|password|passwd)\b\s*[:=]\s*[\"']?([A-Za-z0-9._\-/+]{12,})[\"']?"),
}
This is a floor, not a guarantee. It won’t catch a customer’s name or an internal hostname. Treat the resulting dataset as sensitive regardless.
Also worth saying plainly: check the terms of service of whatever assistant produced your logs before you train on them. Training a local model on your own sessions for your own use is a different question from redistributing the resulting weights, and I’m not offering an opinion on where anyone else’s line is.
Tool-schema grounding
The raw transcripts reference tools by name with no schema. To give the model something to bind to, I generate a <tools> block by observing the actual tool calls in my own logs — counting parameter names and inferring JSON types from the observed values, marking a parameter required if it appears in ≥90% of that tool’s calls. The result is a 31-tool block of roughly 3.2k tokens, prepended to every agent example as a SYSTEM: prefix.
Deriving the schema from observed usage rather than hand-writing it means it matches your actual toolset automatically, including any custom tools.
The final format — and the sharpest footgun
Training format is raw concatenation of context + completion, with the context labels set to -100 so loss is computed on the completion only.
ctx = tok(s[0]["text"], add_special_tokens=False)["input_ids"]
comp = tok(s[1]["text"], add_special_tokens=False)["input_ids"]
ids = (ctx + comp)[:MAXLEN]
labels = ([-100] * len(ctx) + comp)[:MAXLEN]
There is no chat template. Which means any evaluation or inference against this adapter must use /v1/completions with raw text, never /v1/chat/completions. If you wire it up to a chat endpoint you will get garbage and conclude the training failed. I have done this. It is not fun to debug.
Truncation is completion-preserving: budget 15,800 tokens, subtract the tools prefix and the completion, and cut the front of the context to fit, prefixing ...[earlier turns truncated].... Examples whose completion alone exceeds the budget get dropped outright rather than mangled.
Training configuration
| Setting | Value | Notes |
|---|---|---|
MAXLEN |
16384 | memory was never the limit; time is |
GA |
16 | 1 optimizer step = 16 examples |
| gradient checkpointing | unsloth |
off is faster but OOMs at 16k |
SAVE_STEPS |
2 | a deadline kill costs at most 2 steps |
| LoRA | r=32, α=64, attention-only (q,k,v,o_proj) |
6,881,280 trainable params |
| optimizer | adamw_8bit, lr 2e-4, cosine, 3% warmup |
|
| watchdog floor | 18 GB free RAM |
target_parameters=[] is load-bearing
If you’re doing LoRA on a recent MoE with Unsloth, read this bit twice.
Passing target_parameters=[] — an empty list, not None — to get_peft_model is essential. Left as None, Unsloth auto-populates it via get_moe_target_parameters(), which decides whether you want expert LoRA by testing "mlp" in target_modules against a regex it generated itself — and that generated regex always contains the literal "mlp" in its module-type alternation.
That substring false-positive attached LoRA to all 512 experts × 40 layers: 1.85 B trainable params (99.63% of them on experts) and 11 GB checkpoints, none of which I asked for. Passing an empty list short-circuits the auto-detection.
Fixing it cut trainable params 269× and checkpoints 191× (11 GB → 60 MB) — but was only 1.17× faster. Which brings me to:
Throughput: one missing package was the whole ballgame
Qwen3.6-35B-A3B is a linear-attention hybrid — 30 of its 40 layers. Without flash-linear-attention installed, transformers silently falls back to a pure-torch implementation of the gated delta rule. I had been running that fallback since June without knowing.
Installing FLA:
| before | after | |
|---|---|---|
| s/sample @ 16k | 88.5 | 35.1 |
| step time @ GA=16 | ~24 min | ~9 min |
| 1 epoch remaining | ~80 days | ~32 days |
2.52×. No config change, no data cut, no quality tradeoff.
The subtlety that makes this so easy to miss: the components bind independently in the modeling file —
self.chunk_gated_delta_rule = chunk_gated_delta_rule or torch_chunk_gated_delta_rule
— so FLA alone fixes the expensive op even though causal_conv1d is still missing (that conv falls back to a cheap F.silu(self.conv1d(...))).
The warning lies.
is_fast_path_availablerequires all four symbols, including the two fromcausal_conv1d, so"The fast path is not available ..."still prints even with FLA active and the model running 2.5× faster. Judge by s/it, never by that line.
I did not bother installing causal-conv1d: the measured ceiling is 2.68% of step time (2×fwd+bwd across 30 layers = 0.94 s of a 35.1 s sample) even if the kernel were infinitely fast. It also has no aarch64 wheel and hits a catch-22 — its sm_121 flag requires nvcc ≥ 13.0, but the torch build here is cu128, and cross-major-version extension builds are unsupported.
Validate the kernel, don’t just assume it’s correct. FLA’s Triton output vs the torch reference: cosine 0.99998, relative error 0.005, no NaN. On an officially-unsupported arch, “it ran” is not evidence it computed the right thing.
The sm_121 situation generally
GB10 is compute capability 12.1; most of the ecosystem targets ≤ 12.0. Torch prints Found GPU0 NVIDIA GB10 which is of cuda capability 12.1 ... Maximum ... (12.0) on every single run. Things therefore work while quietly taking slow fallback paths. The FLA discovery is exactly that failure mode. If you own a Spark, assume every performance-critical kernel is on a fallback until you’ve measured otherwise.
Unified memory is the real hazard
GPU and CPU share one 121 GB pool. An over-allocation does not raise a clean CUDA OOM — it hangs the entire box. This cost me three reboots in June. A cgroup MemoryMax does not prevent it, because GPU/unified allocations aren’t accounted there.
The only effective protection I’ve found is a dumb polling watchdog that reads free RAM and hard-kills the trainer below 18 GB. Never launch training without it.
Related: bitsandbytes cannot 4-bit-quantize this MoE. The experts are fused nn.Parameter tensors, not nn.Linear, so bnb’s Linear4bit skips ~90% of the model. A “4-bit” load hit 116 GB at 87% loaded (a real one is ~17 GB) — so every QLoRA attempt was silently full-precision, then OOM, then box hang. Unsloth loads the same model at 19.2 GB. That single fact is what killed the Axolotl path for me.
Automation
Two systemd user timers (everything is systemctl --user, with linger on):
ft-night.timer—Mon..Fri 17:00,Persistent=false→ stop server, train to deadline, publish adapter, restart serverft-day.timer— daily05:00→ bring the server up if it isn’t (idempotent safety net)
Persistent=false matters: a missed run is not caught up when the timer is re-armed, which makes it safe to stop the timer temporarily and start it later.
Three things I got wrong first:
KillMode. The vLLM server runs as its own transient unit (systemd-run --user --unit=vllm-serve --collect --property=KillMode=mixed). Launching it as a background child of a Type=oneshot service meant systemd’s default KillMode=control-group tore down the whole cgroup the instant the oneshot exited — the server was killed in the same second it reported ready.
pgrep -f matches the process doing the grepping. The watchdog has its target pattern in its own argv, so a naive pgrep -f unsloth_train.py matched the watchdog itself and the loop never terminated. Orphaned watchdogs then convinced the morning serve job that training was still running. A live check showed that pattern returning four PIDs of which exactly one was python — the others were bash (the watchdog) and timeout (the deadline wrapper). Filter by readlink /proc/PID/exe and exclude your own PID.
Cache paths. Keep HF_HOME pinned explicitly. A redirected XDG_CACHE_HOME once produced a duplicate 67 GB copy of the base model and filled the disk to 97%.
Also: the trainer’s log is appended across nights, so it accumulates one KeyboardInterrupt traceback per night — that is the normal deadline kill landing in loss.backward(). Grepping the whole file for “Traceback” always “finds” failures. Scan only the lines a given night added.
Does it actually work?
I had no idea how to evaluate this, so I picked the simplest thing I could defend and mirrored what the trainer does. If there’s a standard approach I’m reinventing badly, I’d like to hear it.
Method: score the NLL of the reference completion only (context masked, mirroring the trainer’s label masking) under base and adapter, via vLLM /v1/completions with token-id prompts and prompt_logprobs: 0. Held-out set = rows the trainer has not yet consumed, reconstructed with torch.randperm(N, generator=manual_seed(42))[:steps*GA].
At checkpoint-186 — 3.7% of one epoch:
| base | adapter | |
|---|---|---|
| mean NLL | 1.0305 | 0.7336 |
| perplexity | 2.80 | 2.08 |
| wins | — | 24/24 (sign test p ≈ 1e-7) |
Qualitatively, over 12 samples: the adapter emits substantive <think> in 10/12 and a <tool_call> in 9/12; the base emits nothing at all in 6/12.
Two conclusions: the pipeline learns, and adapter-over-NVFP4 is not destructive — the serving assumption I’d been running on faith is now measured.
Now the caveats, because they matter more than the numbers. The base was never trained on this raw concatenated format, so much of that gain is format adaptation, which saturates early. This is not a capability benchmark, and the −28.8% NLL will not extrapolate. Anyone reading a 24/24 win rate as “my adapter is 28% better at coding” has read it wrong — including me, which is why I’m writing it down.
I’m deliberately talking myself down here. A clean 24/24 with a tiny p-value is exactly the kind of result that’s fun to post and easy to over-read, and at 3.7% of one epoch the honest summary is “the plumbing works,” not “the model got better at my job.”
Also: vLLM greedy decoding (temperature: 0) is not bit-reproducible here. Repeated identical requests returned different completions — batch-dependent numerics, more likely to flip near-ties under NVFP4. Judge by rates over N samples, never by a single generation.
The useful takeaway is procedural: re-run this every ~200 steps and stop when NLL plateaus. A data-driven stopping rule beats an arbitrary epoch target, especially when an epoch is this expensive.
Throughput reality, stated honestly
Measured over real nights: ~1,650–1,750 s per optimizer step at 16k sequence, GA=16. An 11.5-hour window yields ~24 steps ≈ 380 examples per night.
At 80,659 examples that’s 5,042 steps for one epoch. On weeknights only, that is ~210 nights — roughly 13 calendar weeks. I’m 6 nights in, at step 186, which is 3.7% of one epoch. Loss has been flat around 0.75–0.85 since step ~115 with grad_norm drifting down.
I want to be blunt about that number because I think it’s the most useful thing here for anyone sizing up a Spark for this kind of work. GPU-hours and calendar time are very different quantities. ~758 GPU-hours remaining sounds tractable. Thirteen weeks of nights is a different kind of commitment, and it’s the one you actually live with.
For me that’s fine — the box would be idle overnight anyway, nothing depends on this finishing, and watching the loss curve with morning coffee is genuinely part of the fun. But “it’s fine because I don’t care when it finishes” is not the same as “it’s fast,” and I’d rather say so than let anyone budget a real project off my numbers.
The levers, in the order I’d reach for them: drop MAXLEN to 8192 (roughly halves step time, but truncated ~45% of my examples last time I tried), subsample the data (76,010 of my 80,659 rows are session logs — there’s obvious room), adopt the plateau-based stopping rule above, or rent a GPU for the bulk run and sync only the ~27 MB adapter back. Cutting LoRA parameter count does not help — the bottleneck is base-model forward/backward at 16k with gradient-checkpoint recomputation.
Things I’m still figuring out
Where I’d most welcome someone telling me I’m doing it wrong:
Whether running a full epoch is worth it at all, given the eval already suggests a plateau-based stop. Whether the 16:1 ratio of session logs to purpose-built traces is diluting the signal I actually care about. Whether attention-only LoRA is the right call on an MoE or just the cautious one. And whether anyone has gotten sequence packing working sensibly with completion-only label masking on this architecture — that looks like the largest unclaimed win, since a lot of my 16k windows are nowhere near full.
None of this is load-bearing for anything. It’s a box in my office learning to imitate my own worst habits, and I’ll keep poking at it either way. But if you’re doing something similar I’d love to compare notes, and if you spot an obvious blunder above, that’s a favor not a criticism.
Happy to share any of the scripts in full if there’s interest. And if you’re running a Spark and haven’t checked whether flash-linear-attention is installed — go check now. That one’s free.