Nightly QLoRA on a DGX Spark: fine-tuning Qwen3.6-35B-A3B on my own coding-agent logs (hobby project)

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 base
  • Qwen3.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_available requires all four symbols, including the two from causal_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 server
  • ft-day.timer — daily 05: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.

Thanks for sharing your journey. QLora is at the top of my todo list to learn about. Below is after discussion with my agent:

This one may have a settings fix. Claude Code has a cleanupPeriodDays key in settings.json that controls how long the local session transcripts are kept, and it defaults to 30 days — almost certainly what pruned your June sessions. Mine is set to 365. It won’t bring back what’s already gone, but it turns “run the extractor monthly or lose data permanently” into an ordinary snapshot habit.

I ran your example-selection rule over my own logs to see what the corpus looks like — one example per assistant turn carrying a tool call or a final answer, same as your parser:

project files MB examples share
A 503 371 37,947 73.6%
B 32 47 4,810 9.3%
C 11 33 3,953 7.7%
D 22 28 3,380 6.6%
20 others 611 28 1,475 2.9%
total 1,179 506 51,565

Mean context ~6.3k tokens, mean completion ~230 tokens — so ~6.5k tokens per example before any tools prefix (with a ~3k schema block like yours, call it ~9.5k). Useful as a second data point against your 80,659, and two things in it surprised me.

One project is 74% of everything. If yours is similarly skewed, that seems worth knowing before worrying about the 16:1 logs-to-traces ratio. It also makes me suspect near-duplicate density is high — hash-dedup on context + completion only catches exact repeats, and a lot of agent work is the same half-dozen moves in slightly different clothes.

The examples are much shorter than the window. ~6.5k (or ~9.5k with a tools prefix) against 16k means a large fraction of every batch is padding. If your distribution is similar, packing looks like a bigger multiplier than you’re assuming — and unlike dropping MAXLEN to 8192 it costs no quality and truncates nothing. My mean already exceeds 8192, so that particular trade would be a bad one for me.

The thing I’d most want to explore, which I didn’t see you mention: filtering the corpus by outcome quality before training on it. The raw turn count isn’t the good-example count. Failed tool calls, turns where you immediately corrected the model, abandoned sessions, late-session turns produced under context rot — all of that is sitting in those 51,565. Most of it looks recoverable from the transcript itself without an LLM judge: did the following tool_result error, did the next user turn read as a correction, was the same tool retried immediately, did the session end in a commit or just stop. Cheap deterministic features, and you could fit something simple over them and rank.

The caveat I’d put on my own idea: don’t drop failures wholesale. That strips every error-recovery trajectory and quietly selects for easy tasks, and recovery is a lot of what makes an agent useful in practice. Dropping only the unrecovered ones seems closer to right.

One smaller thing — your held-out split may drift as the corpus grows. torch.randperm(N, generator=manual_seed(42))[:steps*GA] depends on N, so the next time you re-run the extractor and the pool gets bigger, the permutation changes and “rows the trainer hasn’t consumed” stops meaning what it did. Splitting on a stable hash of the example instead would make appends safe. I haven’t run your pipeline, so I may be misreading it.

Last thought on the eval, and you’re already most of the way there yourself: NLL on held-out completions can show the adapter getting better at your distribution, but not getting worse at anything else — which is the usual way a fine-tune disappoints. Your no-chat-template format makes the obvious complement awkward, since any capability harness is going to want /v1/chat/completions.

Thanks, this is a great reply and the cleanupPeriodDays tip alone was worth posting for. I genuinely didn’t know that setting existed. Default 30 days explains my situation exactly — my two exports were 34 days apart, so of course they barely overlapped. I’d been treating it as some mysterious rotation policy I had to out-run with a cron job, and it turns out it’s one line in settings.json. Mine’s set to 365 now. Worth flagging for anyone else copying my setup: don’t set it to 0 hoping to disable cleanup, that used to silently turn off transcript persistence entirely and now just errors.

Your corpus numbers made me go measure mine properly instead of trusting what I’d written in the post, and I found something dumb that I think changes the packing conversation.

I sampled 800 rows out of final_full.jsonl. Context length has a hard spike at exactly 36,832 characters, and 71% of examples sit right on it. That’s 12,832 for my tools block plus 24,000 — and 24,000 is MAX_CTX_CHARS in cc_to_sft.py, a constant I set in the very first version of the parser and never revisited. Meanwhile only 0.1% of rows carry the truncation sentinel from the tokenizer budget I actually designed. So that 15,800-token budget has essentially never fired. The parser has been throwing away context at ~24k chars this whole time, about half of what the budget allows, and I bumped MAXLEN to 16384 to stop truncating examples that were already truncated upstream. Nice.

The other number is worse. 63% of my completions are under 400 characters, and at the median the completion is 0.7% of the example — by mean it’s 2.5%. So ~97% of every forward and backward pass is masked context that contributes nothing to the loss, and roughly 38% of each pass is the same tools block, re-tokenized from scratch for every single example.

Worth saying I don’t think the fix is just raising that 24k cap. Completions don’t grow when context does, so that would roughly double compute per example for identical loss signal and take the trained fraction down to ~1.3%. It’s the wrong end of the problem.

Which brings me to the one place I think you’re off: I don’t believe I’m paying for padding. My trainer runs per_device_train_batch_size=1 with GA=16, so it’s 16 independent single-example passes, and DataCollatorForSeq2Seq pads to the longest sequence in the batch — which is the example itself. No padding anywhere. So packing unrelated examples together wouldn’t recover wasted tokens for me, it’d just improve arithmetic intensity, which I’d guess is worth tens of percent rather than the ~1.8x the window math suggests.

But you’re pointing at something real, just one level up. The fix isn’t packing unrelated examples, it’s consolidating multiple assistant turns from the same session into one example with each completion unmasked. Attention is causal, so training on a session with N turns unmasked gives the identical per-token loss to my N separate examples — same gradient — but in one pass instead of N, with the tools block read once instead of N times. On paper that’s a few-fold cut in tokens processed per trained token. Haven’t built it yet, so grain of salt, but it’s now top of my list and it’s a much better answer to my own “is packing worth it” question than packing was.

You’re also right about the held-out split, and it’s worse than you thought. torch.randperm(N) shares nothing between different N, yes — but build_full.py also does random.seed(42) and shuffles a pool whose size changes, so there are two N-dependent shuffles stacked. Both break the moment I append new logs. Going with your stable-hash suggestion, or possibly just writing a held-out file once and excluding it at build time, which is dumber and harder to get wrong.

The outcome-quality filtering idea is the one I’ll be chewing on longest, and your caveat is the important half — dropping all failures would strip every error-recovery trajectory and quietly select for easy tasks. One thing that makes it cheaper than it looks: the parser walks the transcript in order, so at the moment it emits an example it already has the next tool_result and the next user turn sitting right there. The lookahead is free, I just throw it away today. Adding “did the following tool call error” and “did the next user turn look like a correction” as flags is maybe twenty lines.

On the eval — fair hit, and it’s the thing I’m least happy with. One workaround I hadn’t considered until you pushed on it: most standard benchmarks (MMLU, ARC, HellaSwag) are loglikelihood tasks rather than chat tasks, and lm-eval-harness will score those against a raw /v1/completions endpoint without ever needing a chat template. Since I’m already serving base and adapter side by side, that’s a pretty cheap regression check. Adding it.

Thanks again — the settings fix alone saved me a recurring chore, and I’d have kept optimizing the wrong end of the pipeline for weeks without your numbers to compare against.

Fair hit on the padding — you’re right, batch size 1 with pad-to-longest means there’s nothing to pack out. I reasoned from window size without checking your batch config.

Which leads to what I actually wanted to ask. Is per_device_train_batch_size=1 a memory constraint or just where you landed?

I ask because working your numbers back — 262k tokens per step, 3B active, ~1,700s — lands somewhere around 3-4 TFLOPS effective against a part that should do well over a hundred. If that’s roughly right, the bottleneck isn’t parameter count, it’s that batch-1 on a 256-expert MoE gives each expert a handful of tokens per step. Which would make the calendar problem a utilisation problem.

So: did you consider a small dense model instead? A 4B dense has slightly more active compute per token than 35B-A3B’s 3B, but every GEMM is full-width and it fits a real batch size. Curious whether you ruled that out early and why.

Which is really a question about the goal. What does “it worked” look like to you? A local model you’d actually hand a task to instead of Claude, or something narrower — your tool-call conventions, your file-layout habits, the mechanical parts? Those want very different models and very different amounts of patience.

And a related one I’ve been chewing on: how much of what you’re trying to teach could be a rule in CLAUDE.md or a hook instead? I keep landing on the view that fine-tuning’s real job is whatever’s left after you’ve written down everything writable — but I don’t have a principled way to draw that line, and you’ve thought about this longer than I have.

What would the ideal external training system need to guarantee before you would move the bulk run off your Spark?

Yeah, batch size 1 is just inertia. It dates from when bitsandbytes was loading the model at full precision and hanging the box, so I set everything to the smallest number that stopped the crashing and never revisited it.

Your TFLOPS math is close but two of the inputs pull opposite ways. 262k tokens per step assumes every example fills the 16k window, and mine average about 8.4k, so it’s closer to 135k. And 1,700s was right for pre-FLA, but I just got a full night with FLA in place and it’s 611 s/step now. Comes out around 5.3 TFLOP/s instead of 3-4. Still terrible, so your point stands.

The number that actually got me: at a 2.5% trained token fraction I’m producing about 5 tokens of real loss signal per second. Five. On a 4,000 dollar machine.

No, I didn’t consider a dense 4B, and I ruled out dense for a bad reason. I already had the NVFP4 quant built and serving, so training the same base meant hot swapping an adapter instead of standing up a second serving path. That’s a deployment convenience making a training decision. You’re probably right that a 4B dense with a real batch size trains in hours, and I’d have run five experiments by now instead of one.

On the goal, I don’t have a good answer, and that’s a bigger problem than any of the config stuff. It started as a learning project, the learning happened, but somewhere I started treating the adapter as the point and never wrote down what it would have to do for me to call it done.

Being straight: if the target is a local model I’d hand real work to instead of a frontier model, no number of epochs gets a 3B active student there by copying a much bigger teacher. You can clone what an answer looked like, not the thinking that produced it. Best case is something that fails confidently in the right format, which is worse than failing obviously, because I’d stop checking.

If the target is the narrow stuff, my tool conventions and file habits, that’s reachable. Probably on 3k good examples, not 80k unfiltered ones.

Your CLAUDE.md framing is right and I don’t have a better line either. The test I keep landing on is whether I can name a behavior I want that I can’t write down as a rule. When I actually try, most of my list is writable. And a rule stays current when my toolset changes, which a 14 week run does not.

Whatever is left after you subtract everything writable is smaller than I wanted it to be. Probably the honest answer to your first question too.

Thanks for asking the annoying version instead of the polite one.

Happy to be a foil. We are all on this learning journey together. :)