Skip to content

feat(packaging): add single-file llama.cpp GGUF export - #6045

Draft
ZX-ModelCloud wants to merge 3 commits into
mainfrom
feat/gguf-package
Draft

ZX-ModelCloud wants to merge 3 commits into
mainfrom
feat/gguf-package

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds gptqmodel.package(GGUFPackageConfig(...)), which turns a GPT-QModel GGUF checkpoint directory into one llama.cpp-readable .gguf file.

+2638 / -1 across 12 files: a new gptqmodel/packaging/ package (config, errors, architecture registry, tokenizer metadata, writer), docs/gguf-package.md, and tests/test_gguf_package.py.

Fixes #6046
Fixes #6047
Fixes #6048

What Changed

  • New public API: PackageConfig(model_path, out_path, overwrite=False) holds the in/out paths; GGUFPackageConfig adds the tokenizer, architecture override, dense dtype, alignment, name, file type and extra metadata; gptqmodel.package(config) dispatches on the config type and rejects a type it has no writer for.

  • The writer is a container change, not a conversion: a GPT-QModel GGUF linear already stores ggml block bytes in qweight ([out_features, bytes_per_row] uint8), so packaging only renames tensors, reorders whole output rows where an architecture requires it, stores dense tensors, and writes the architecture and tokenizer metadata. No weight is dequantized or re-quantized.

  • Verified layouts: qwen2, qwen3, llama (Llama includes the q/k rotary-interleave row permutation for weights and biases, and the Llama-3 rope_freqs table). An architecture without a registered layout is refused by default; allow_unverified_arch=True uses the generic name map and metadata with no weight transform.

  • Fail-closed contract: an unregistered architecture, a mixture-of-experts checkpoint, a padded or otherwise mismatched packed row, an unmapped tensor, a duplicate output name, or a missing gguf dependency fails before a file is published. A read-back check verifies names, ggml types and logical shapes before publication. Publication with overwrite=False claims the destination atomically. Writer, verification and publication failures run temporary-file cleanup.

  • The tokenizer is read from the checkpoint directory (or tokenizer_path=/tokenizer=) and never executes checkpoint code. Fast BPE tokenizer rows past the vocabulary are marked unused so the token list matches the embedding. SentencePiece and WordPiece vocabularies are rejected.

  • docs/gguf-package.md documents the flow, the byte-safe operation table and the failure contract; it is linked from README.md and docs/README.md.

  • The writer reads current rope_parameters and supports default and linear RoPE plus Llama-3 scaling on Llama. Qwen2 and Qwen3 require full attention and their architecture-specific tensors. Packed payloads must be uint8 and use types llama.cpp can serve as weights. Generated metadata keys are reserved.

Mixture-of-experts packing, multimodal mmproj files and re-quantization are outside the scope of this export.

Tests

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.
$ bash format/check.sh
All checks passed!

$ python -m pytest tests/test_gguf_package.py tests/test_internal_gguf.py tests/test_gguf_load_policy_env_removal.py tests/test_gguf_all_formats.py -o addopts= -o log_cli=false -q -rs --tb=short
1032 passed, 14 skipped

The package, reader and load-policy suites passed all 89 cases, including llama.cpp load, token ID parity and evaluation on Qwen2, Qwen3 and Llama fixtures. The format suite passed 943 cases. Its 14 skips cover two extreme-value IQ3 cases and 12 combinations without a native ggml matmul implementation.

Invariant Regression Pre-fix result Fixed result
RoPE and attention semantics test_current_rope_parameters_set_frequency_base, test_llama3_rope_freqs_matches_the_piecewise_spec, test_linear_rope_scaling_is_preserved, test_refuses_unsupported_attention_layout Lost current fields or accepted an incompatible layout. The legacy Llama-3 control passed. Passed
Packed type and required tensors test_refuses_non_byte_packed_storage, test_refuses_activation_only_ggml_types_as_weights, test_refuses_missing_required_attention_tensors, test_absent_tie_flag_uses_the_model_default Cast packed storage, accepted missing tensors or mishandled activation-only types. Passed
Runtime metadata test_refuses_metadata_that_replaces_generated_fields, test_signed_extra_metadata_round_trips, test_refuses_sentencepiece_tokenizers_without_a_gguf_vocabulary Overwrote generated metadata, failed to serialize signed integers or produced an incompatible vocabulary. Passed
Atomic publication and retry test_output_created_during_verification_is_preserved, test_writer_failure_leaves_existing_output_and_cleans_temp_file Replaced an existing destination or leaked a temporary file. Passed
Model defaults test_implicit_model_defaults_are_written, test_llamacpp_loads_the_packaged_file Omitting context length and RMSNorm epsilon produced files that llama.cpp could not load for all three model families. Native load and evaluation passed.
MLP activation test_refuses_unrepresentable_mlp_activation All three architectures accepted GELU even though their target graphs use SiLU. All three reject the export.
Derived buffers test_only_known_derived_buffers_are_ignored A weight whose name shared the rotary buffer prefix disappeared from the output. The known buffer is ignored and the unknown weight raises before publication.

Measured Impact

Not applicable: this change adds an export path and makes no VRAM, performance or accuracy claim. The packed payload is copied, and the tests assert byte equality rather than error statistics.

Model Support / Module Plan

Not applicable: no MODEL_MAP entry, model type, alias, definition or fusion eligibility changes. The architecture registry in gptqmodel/packaging/arch.py is local to the export path and does not affect model loading or quantization.

AWQ onboarding safety

Not applicable: no AWQ grouping, search, replay or folding changes.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.
  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct from success.
  • A reference page under docs/ repeats the diagrams, titled for the mechanism, and is linked from README.md.

Before this change there was no single-file export at all: a llama.cpp artifact could only be produced by re-converting the dense model with llama.cpp's convert_hf_to_gguf.py, which re-quantizes every weight. The new entry point consumes the existing packed checkpoint instead.

Stage Before After
Single-file llama.cpp artifact not produced by GPT-QModel; required a dense re-conversion package() writes it from the existing packed checkpoint
Weight transform full re-quantization byte copy; only whole output rows may move
Unsupported layout dense re-conversion required rejects layouts the export cannot represent
RoPE resolution arch.py:109 and gguf_package.py:724 read legacy fields ArchSpec.extra_metadata and LlamaSpec.extra_tensors share current configuration precedence
Output publication gguf_package.py:631 checked before an unconditional replace at line 691 _write_gguf claims an unused destination or explicitly replaces it after verification
flowchart TD
    A["gptqmodel.package(GGUFPackageConfig)"] --> B["_package_gguf reads config.json and quantization_config"]
    B --> C{"GPT-QModel GGUF checkpoint?"}
    C -- "no" --> R1["CheckpointFormatError"]
    C -- "yes" --> D["_resolve_arch and resolve_spec"]
    D --> E{"Registered layout or explicit opt-in?"}
    E -- "no" --> R2["UnsupportedArchitectureError"]
    E -- "yes" --> W["ArchSpec.validate_layout and _build_tokenizer_metadata"]
    W -- "incompatible" --> R3["Reject the layout"]
    W -- "valid" --> F["_plan_tensors checks names, storage, required tensors and shapes"]
    F -- "incompatible" --> R3
    F -- "valid" --> H["_write_gguf writes metadata, tensor info and payloads to a temporary file"]
    H --> I["_verify_written reads names, ggml types and shapes"]
    H -- "write fails" --> R4["Remove temporary file"]
    I -- "verification fails" --> R4
    I -- "verified" --> J{"overwrite?"}
    J -- "yes" --> K["os.replace publishes the file"]
    J -- "no" --> L["os.link publishes at a free destination"]
    K -- "publication fails" --> R4
    L -- "destination already exists" --> R5["FileExistsError and temporary file cleanup"]
    L -- "other publication failure" --> R4
    L -- "published" --> M["Remove temporary link"]
    classDef bad fill:#fdd,stroke:#c00,color:#111;
    class R1,R2,R3,R4,R5 bad;
Loading

The same diagram and the full situation-to-result table are in docs/gguf-package.md.

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

Not applicable: no kernel, dispatch, packer or fusion change. The writer copies packed bytes and does not execute a kernel.

Notes

  • A single-file GGUF is a different container by definition. The requested deliverable is a llama.cpp artifact, so this is the one publish path that is not safetensors; nothing else changes its container.
  • Every option is a config field; no GPTQMODEL_* environment switch is introduced or read.
  • gguf>=0.19.0 (already the [gguf] extra floor) provides the writer and the tensor-name map. The writer is imported lazily, so import gptqmodel does not require the extra.
  • Reviewers: gptqmodel/packaging/arch.py is the extension point for a new architecture (metadata, row permutation, generated tensors, expected shapes). gptqmodel/packaging/gguf_package.py::_check_shape is the single place that decides whether a layout is byte-safe.

Add gptqmodel.package(GGUFPackageConfig(...)), which writes one llama.cpp-readable .gguf file from a GPT-QModel GGUF checkpoint. The packed payload is already ggml block bytes, so packaging only renames tensors, reorders whole output rows where an architecture requires it (Llama q/k rotary interleave, including biases), stores dense tensors, and writes the architecture and tokenizer metadata. No weight is dequantized or re-quantized.

Refusals are part of the contract: an unregistered architecture, a mixture-of-experts checkpoint, a padded or otherwise mismatched packed row, an unmapped tensor, or a missing dependency fails before a file is published. The output is written to a temporary file and renamed only after a read-back check of names, ggml types and logical shapes.

Verified layouts: qwen2, qwen3, llama. docs/gguf-package.md documents the flow and failure contract; tests/test_gguf_package.py covers byte preservation, row permutation, tokenizer arrays and every refusal.

@ZX-ModelCloud ZX-ModelCloud left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed the two writer cleanup findings, atomic publication, and GGUF compatibility checks for RoPE, packed weights and tokenizer metadata. The GGUF regression suites, llama.cpp checks for Qwen2, Qwen3 and Llama, and format/check.sh passed.

@ZX-ModelCloud ZX-ModelCloud left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed #6046, #6047 and #6048 in 50f9c5f. Qwen2, Qwen3 and Llama now load in llama.cpp when context length and RMSNorm epsilon are omitted. Export also rejects unsupported MLP activations and unknown weights that resemble derived buffers. GGUF suites passed 1,032 tests with 14 skips. Ruff passed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant