Trace-Expander-4B

A chain-of-thought expander for agents: give it the prompt and the response the agent is about to emit β€” a tool call or a final answer β€” and it writes the reasoning trace that should precede it, wrapped in <|think|>...<|/think|>. Built on Qwen/Qwen3.5-4B with LoRA adapters trained on public thinking datasets. The transcript may already contain expanded blocks from earlier turns, or it may not: the trace tokens are ordinary special tokens in the prompt span, so the same loaded model serves sequential expansion (existing blocks visible) and parallel expansion (independent calls, no shared state). Both shapes were tested against this artifact.

Specification Trace-Expander-4B
base model Qwen/Qwen3.5-4B (32 layers, hidden 2560, hybrid linear/full attention)
adapter LoRA rank 16, alpha 32, dropout 0.05 on q/k/v/o/gate/up/down
adapter parameters 21,233,664 LoRA + 46,080 embedding rows (9 rows x 2 tables)
vocabulary 248,086 (248,077 base + 9 trace tokens)
special tokens prompt, response, think open, think close, length x5
length buckets small / medium / large / xl / xxl at trace token edges 128 / 256 / 512 / 1024
base weights at serve native NVFP4 (packed once, torch._scaled_mm, no dequantize loop); floating-point fallback
adapter file size 41 MB
training 2 x 2000 steps, seq 2048: open-thoughts + numina-math + smoltalk-think
holdout eval loss 0.5235 (128 examples)

Quick start

pip install -r requirements.txt

# Inspect model specifications
python infer.py --info

# Expand a trace
python infer.py --prompt='What is the capital of France?' --response='Paris' --length=small

# Agentic: response is a tool call, transcript already has an earlier block
python infer.py --prompt="$TRANSCRIPT" --response='{"tool": "edit_file", "args": {"path": "config.py"}}' --length=xl

# Machine-readable output
python infer.py --prompt='What is 17 + 25?' --response='42' --json --device=cpu

The first run downloads Qwen/Qwen3.5-4B from Hugging Face (about 8 GB). Everything else is in this directory: infer.py carries the complete model assembly β€” LoRA injection, adapter loading, NVFP4 packing, generation β€” and reads its shape from config.json.

--quant=nvfp4 (the default from config.json) needs a GPU with torch._scaled_mm and torch.float4_e2m1fn_x2 (RTX 50-series). On anything else the release prints a notice to stderr and runs the floating-point base with the same adapters.

from infer import TraceExpander, render_cot

expander = TraceExpander(device="auto")

# fresh prompt, no existing blocks
text = expander.expand(
    "You are an agent with tools bash and read_file.\nuser: check why CI fails",
    '{"tool": "bash", "args": {"cmd": "pytest -x -q"}}',
    length="medium",
)
trace, tail = expander.parse(text)

# sequential: the transcript already carries an earlier expanded block
prior = render_cot("the tool result shows exit code 1", '{"tool": "bash", "args": {"cmd": "pytest -x"}}')
text = expander.expand(f"transcript:\n{prior}\nuser: now fix it", "the default batch size is wrong", length="xl")

expand() always returns the wrapped block plus the response you passed in; the model generates only the trace. One loaded TraceExpander is safe to share across threads β€” the logits ramp processor and sampling state are built per call.

Sample output

Fresh prompt, --length=small, default sampling, NVFP4:

<|think|>The capital of France is Paris. It is located in the north-central region of the country and serves as the nation's political, cultural, and economic center. Known for its rich history, iconic landmarks like the Eiffel Tower and the Louvre Museum, and its bustling fashion and culinary scenes, Paris is one of the world's most visited cities.<|/think|>

Paris

Agentic, sequential shape β€” transcript contains an earlier render_cot block ending in a read_file tool call, followed by tool result: DEFAULT_BATCH = 4, response is the fix:

<|think|>Okay, I need to fix the failing assertion which is comparing the default batch size against 8. The user says to inspect the config. Let me see what the current value of DEFAULT_BATCH is. Oh right, when I read the config.py file, the DEFAULT_BATCH was set to 4. So the problem is that the default batch size is 4, but the test expects it to be 8. So the solution is to change DEFAULT_BATCH from 4 to 8...<|/think|>

{"tool": "edit_file", "args": {"path": "config.py", "old": "DEFAULT_BATCH = 4", "new": "DEFAULT_BATCH = 8"}}

The generated trace conditions on the embedded block instead of being confused by it. The same holds in parallel: two expansions from one loaded model over a ThreadPoolExecutor each stayed on their own topic with the correct response tail.

How it works

Input layout, one sequence:

<|prompt|> prompt tokens <|response|> response tokens <|len_m|> <|think|> trace tokens <|/think|>

Only the trace tokens and the close tag carry loss; the prompt, response, and any embedded earlier blocks are masked context. Training packed the base weights to NVFP4 once and never dequantized them: every linear runs torch._scaled_mm against a pre-packed weight with a per-call activation quantise (compiled, with the validated eager chain as fallback). At serve time the same pack runs on load, in both the forward and transpose orientations the kernels need.

Generation conditions on your prompt, your response, and a length bucket, then samples the trace until the close tag. A WrapItUpProcessor ramps the close-tag logit +20 across the second half of the token budget, so short budgets wrap up and long budgets are free to run long β€” the bucket is a soft steer, --max-new is the hard bound.

The nine trace tokens are added to the Qwen vocabulary; their embedding rows are trained alongside the LoRA weights (9 rows x 2 tables, 46,080 parameters, row-masked Adam updates) and shipped inside the checkpoint.

Quality

measurement value
holdout eval loss (shipped run, 128 examples) 0.5235
holdout eval loss (prior fresh run, 128 examples, separate measurement) 0.5061
training loss, resumed run 0.3254 (fresh start) -> 0.2358 (final)
agentic matrix, all shapes 7/7 wrapped, response tails intact
length buckets (17 + 25 -> 42) small 47 chars, medium 45, large 45, xl 290, xxl 560

The agentic matrix on this artifact: fresh prompt with a tool-call response, fresh prompt with a final-answer response, both again with an existing trace block in the transcript, a parallel pair, and an unclosed-block edge case β€” every one produced a parseable wrapped trace ending in the exact response it was given.

Limitations

  • No agent data in training. The corpora are math and everyday-thinking datasets (open-thoughts, numina-math, smoltalk-think). Agentic prompts work mechanically β€” the matrix above passes β€” but on fresh agent instructions the trace can drift into format meta-commentary ("the command should return only the thought process, no tool calls in the response") instead of pure reasoning. A small slice of real tool-call transcripts is the fix; this release does not have it.
  • It is an expander, not a decider. The response is given as conditioning; the model writes the trace that leads to it. It never chooses the action.
  • NVFP4 needs RTX 50-series. Without torch._scaled_mm + torch.float4_e2m1fn_x2 the release falls back to floating-point weights; outputs stay valid but differ slightly from the quantized path the adapters were trained against.
  • Soft length control. Buckets steer via the close-tag ramp; they are not guarantees. Use --max-new for a hard cap.
  • Small holdout. 0.5235 is measured on 128 examples drawn from the training distribution; it is a health check, not a benchmark.

Training

Trained in the MythosMini repository with python train.py --trace: 2 x 2000 optimizer steps at sequence length 2048 (the second window resumed from the first via --resume), LoRA r16 / alpha 32 / dropout 0.05 over q/k/v/o/gate/up/down with the base frozen and quantized to NVFP4, loss masked to trace plus close tag, row-masked Adam on the nine trace embedding rows, adapter checkpoint written before the holdout eval so an eval OOM cannot lose the run. config.json beside this file carries the hyperparameters and the recorded numbers.

Files in this Release

  • infer.py: Standalone inference CLI and Python interface (model assembly, NVFP4 packing, generation).
  • config.json: Shape, tokens, generation defaults, training and eval numbers.
  • tokenizer.json: Qwen vocabulary plus the 9 trace tokens.
  • Trace-Expander-4B.pt: The 41 MB adapter checkpoint (LoRA weights + trace embedding rows).
  • requirements.txt: Python package dependencies (torch, transformers, tokenizers).
  • README.md: You are here.
Downloads last month
48
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Collection including Glint-Research/Trace-Expander-4B