blacksmith-1a / docs /GGUF.md
bctnry's picture
Upload folder using huggingface_hub
2054ea3 verified
|
Raw History Blame Contribute Delete
6.98 kB
# GGUF export for llama.cpp
Blacksmith's `NanoGPT` is not a Hugging Face architecture, so
`convert_hf_to_gguf.py` cannot read it and there is no upstream `blacksmith`
architecture in llama.cpp. The closest match is **`gptneox`**, which shares
every structural choice that matters:
| property | NanoGPT (`model.py`) | llama.cpp `gptneox` |
|---|---|---|
| norm | LayerNorm (with bias), eps 1e-5 | `LLM_NORM` + bias |
| FFN | Linear → GELU → Linear, no gate | `LLM_FFN_GELU` + `LLM_FFN_SEQ` |
| RoPE | **interleaved** (pairs `2i, 2i+1`) | **half-split** (pairs `i, i+d/2`) — converted, see below |
| residual | sequential (attn, then ffn) | `use_parallel_residual = false` |
| embeddings | untied input/output | `token_embd` + `output` |
| attention | MHA, no GQA | `head_count_kv = head_count` |
`convert_to_gguf.py` maps the checkpoint onto that architecture and
`verify_gguf.py` checks the result without needing llama.cpp.
## Export
```zsh
# pretrained / 32k checkpoint: advertise the length it was trained at
python3 convert_to_gguf.py --ckpt blacksmith-1_lc32k.pt \
--context-length 32768 --out blacksmith-1-32k.gguf
# 128k via YaRN on top of the 32k checkpoint
python3 convert_to_gguf.py --ckpt blacksmith-1_lc32k.pt \
--context-length 131072 \
--rope-scaling yarn --rope-factor 4 --rope-orig-ctx 32768 \
--out blacksmith-1-128k.gguf
```
`--dtype f16` (default) is exact for these weights: the checkpoint is bf16, and
f16 has a wider mantissa, so the round-trip is bit-accurate for in-range values
(`verify_gguf.py` reports max |diff| ≈ 3e-8, i.e. the bf16→f32 rounding).
## What the metadata means
Two independent fields decide what a runtime does with the context window:
- `gptneox.context_length` → `hparams.n_ctx_train`. This is the number tools
display and the value `-c/--ctx-size` is compared against. If the file says
32768, a 128k run logs `possible training context overflow` even when it works.
- `gptneox.rope.scaling.{type,factor,original_context_length,attn_factor}` →
applied automatically at load (`llama-context.cpp` falls back to
`hparams.rope_freq_scale_train` and `hparams.rope_scaling_type_train` when
no CLI override is given).
So a file can legitimately declare `context_length = 131072` while the weights
were trained to 32k, **provided** the YaRN block is present and correct. The
equivalent CLI for a file that declares only 32k is:
```zsh
llama-cli -m blacksmith-1.gguf -c 131072 \
--rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
```
llama.cpp then re-labels the model internally
(`n_ctx_train = n_ctx_orig_yarn / rope_freq_scale`).
### `original_context_length` must be the trained length
`model.py` builds YaRN tables with `original_max_pos = max_seq_len`, which is
4096 in `hyperparameters.py`. After the long-context phases the model is
trained at 32768, so the ramp has to be computed against **32768**, otherwise
the wrong frequency bands get interpolated. `generate.py` currently needs an
`--original-max-pos` flag for 128k testing; the GGUF export takes
`--rope-orig-ctx` explicitly for this reason.
## Validation status
`verify_gguf.py` checks, against the PyTorch checkpoint:
- every tensor exists with the right shape (244 tensors, 20 blocks)
- values match after the documented transpose, the Q|K|V concatenation and the
rope permutation
- the fused `attn_qkv` row order matches what `build_qkv()` expects
(Q rows, then K, then V — see `src/llama-graph.cpp`)
- all metadata llama.cpp reads for `gptneox` is present
- the four added tokens (`<|im_start|>`, `<|im_end|>`, ` thinking`, `</think>`)
land at ids 50257–50260, matching `tokenmaker.py`
```zsh
python3 verify_gguf.py blacksmith-1-128k.gguf blacksmith-1_lc32k.pt # PASS
```
**Numerical validation (done).** `llama-perplexity` and the PyTorch model now
agree on the same 512-token window:
| implementation | PPL |
|---|---|
| PyTorch (`model.py`) | 19.34 |
| llama.cpp, `gptneox` GGUF | 19.33 |
The remaining 0.01 is f16 storage plus the uint16 logit quantisation used by
the perplexity tool. Getting there surfaced three bugs that a shape-level check
could not have caught:
1. **f16 biases.** llama.cpp's CPU backend builds f32 activations and aborts on
an f16 bias (`binary_op: unsupported types: dst: f32, src0: f32, src1: f16`).
All 1-D tensors are now written f32, only the 2-D weights are f16.
2. **Wrong pre-tokenizer.** Without `tokenizer.ggml.pre = "gpt-2"`, llama.cpp
falls back to its default regex and splits `" 31"` into `['Ġ','31']` instead
of `['Ġ31']` — a 512-token text became 535 tokens. The value is `"gpt-2"`
with the hyphen; `"gpt2"` is rejected as an unknown pre-tokenizer type.
3. **RoPE pairing, the big one.** `model.py` rotates interleaved pairs
`(x[2i], x[2i+1])`; llama.cpp's `LLAMA_ROPE_TYPE_NEOX` — despite the name —
rotates half-split pairs `(x[i], x[i+d/2])`. Feeding the weights unchanged
gave PPL **135.5** instead of 19.3 while every tensor still had the right
shape. `convert_to_gguf.py` now permutes the output dims of `Wq`/`Wk` (and
their biases) per head, which is the change of basis between the two
conventions and leaves Q·K invariant. Confirmed by forcing half-split rope
in PyTorch: PPL 135.36 vs llama.cpp's 135.52 on the same file.
### Known deviation: `head.bias` is dropped
`model.py`'s `head` is an `nn.Linear` with a bias, and llama.cpp's `gptneox`
graph applies `output` without one. Measured on the step-75600 checkpoint in
`drop_output_bias` terms: max |Δlogit| = 0.067, top-1 and top-5 unchanged,
KL(p‖q) ≤ 1.4e-4. `convert_to_gguf.py` prints the dropped magnitude so it is
never silent. If exactness matters, the alternative is a small llama.cpp patch
that adds an optional `output.bias`.
## Context budget
At 128k the KV cache, not the weights, is the constraint. With 20 layers, 10
heads, head_dim 128 and no GQA:
```
20 × 2 (K,V) × 1280 × 2 bytes × 131072 ≈ 13.4 GB (f16 KV)
```
`--cache-type-k q8_0 --cache-type-v q8_0` ≈ 6.7 GB, q4 KV ≈ 3.4 GB. The f16
weights are ~1 GB; a Q4_K_M quantisation is ~330 MB.
## Chat format
`sft_dataset.py` formats turns as `<|im_start|>{role}\n{content}<|im_end|>\n`
and terminates a conversation with EOT (50256); `generate.py` additionally
places an EOT before each user turn, which is just the previous conversation's
terminator. The template embedded in the GGUF reproduces that, so a fresh chat
starts at `<|im_start|>`:
```
{% for message in messages %}<|im_start|>{{ message['role'] }}
{{ message['content'] }}<|im_end|>
{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
{% endif %}
```
Use `--no-chat-template` if you want to drive the prompt tokens yourself.
## Quantisation
Once a llama.cpp build is available:
```zsh
llama-quantize blacksmith-1-128k.gguf blacksmith-1-128k-Q4_K_M.gguf Q4_K_M
```
Quantise **after** the export, not before: f16 keeps the export verifiable
against the checkpoint.