self-review-skill / transformers_contribution_skill.md
Molbap's picture
Molbap HF Staff
Upload transformers_contribution_skill.md
92e16d7 verified
|
Raw
History Blame Contribute Delete
32.5 kB
---
name: transformers-contribution-review
description: Self-review a contribution to huggingface/transformers before opening or updating a PR. Runs policy checks, v5 API-conformance checks, dead-code tracing, and a verification pass over your branch, then reports findings by severity with a READY / NEEDS CHANGES verdict. Use it yourself or hand it to your AI assistant β€” especially if AI wrote any of the code. The review pass is report-only; fixing happens after, deliberately.
---
# Transformers contribution self-review
Run this against your branch **before** opening a PR and again before every review round you push. It mirrors what maintainers check, so you catch issues before a human does. If an AI assistant produced any part of the change, running this is not optional: per [CONTRIBUTING.md](CONTRIBUTING.md), pure agent PRs are not accepted, the human submitter must be able to defend every line, and AI assistance must be disclosed in the PR description. Breaching the agent contribution guidelines can result in automatic banning.
Three disciplines up front:
- **Everything here is checkable with commands.** A check you did not run is a check that failed β€” do not tick it from memory.
- **The review pass is report-only.** Review the whole diff, write the report (section 14), *then* fix the blocking items deliberately. Reviewing and editing in the same pass is how findings get silently half-fixed.
- **Do not invent issues and do not flag pure style** β€” formatting is `make style`'s job. Findings are correctness, API conformance, and dead weight, each anchored to a `file.py:line`.
Reference documents this skill leans on β€” read the one that matches your change, fresh, not from a remembered copy:
- [docs/source/en/modular_transformers.md](docs/source/en/modular_transformers.md) β€” authoring models with modular files
- [MIGRATION_GUIDE_V5.md](MIGRATION_GUIDE_V5.md) β€” the v5 API surface: what was removed, what replaced it
- [src/transformers/conversion_mapping.py](src/transformers/conversion_mapping.py) β€” the per-architecture checkpoint-conversion registry
- [src/transformers/core_model_loading.py](src/transformers/core_model_loading.py) β€” the loading machinery: `WeightRenaming`, `WeightConverter`, and the ops (`Chunk`, `Concatenate`, `PermuteForRope`, …)
## 0. The tenets
Transformers is built on eight [design tenets](https://huggingface.co/blog/transformers-community/Transformers-tenets). They are not aspirational β€” reviews reject code that violates them, so check your diff against each one before a human does:
1. **Source of truth.** Model implementations must be faithful to the original performances. For your PR this means numerical parity against the reference implementation, proven with numbers, and integration tests that pin those numbers. A model without a parity test is not done.
2. **One model, one file.** All core inference logic is readable top-to-bottom in one generated file. Model-specific logic pulled into a shared utility the reader must chase across files is a violation. Modular files do not conflict with this: the generated `modeling_*.py` is still one self-contained file; `modular_*.py` is the authoring format.
3. **Code is the product.** Optimize for reading, diffing, and tweaking. Full-word variable names (`hidden_states`, not `x`), no dead parameters, no collapsed control flow that hides a branch. Readability regressions are findings even when behavior is unchanged.
4. **Standardize, don't abstract.** If it is model behavior (a novel attention, a special mask), it stays in the modeling file β€” do not build an abstraction layer around it. If it is generic infrastructure (task heads, output capture, mask creation, checkpoint conversion), use the standardized helper β€” do not reimplement it inline.
5. **Do repeat yourself β€” through the sanctioned mechanisms.** Duplication that keeps a model file readable is fine, but it must be kept in sync: that is exactly what `modular_*.py` and `# Copied from` are for. A near-duplicate architecture that one conversion-mapping line or one modular inheritance would collapse is a violation.
6. **Minimal user API.** Config, model, preprocessing; `from_pretrained`, `save_pretrained`, `push_to_hub`. Every new public method, constructor argument, or codepath a user must learn is a cost. Prefer extending the standard flow over adding a parallel one β€” no bespoke `chat()` helpers, no custom loading entrypoints, no sampling parameters as method arguments (they belong in a `GenerationConfig`).
7. **Backwards compatibility.** Public APIs evolve additively. Anything that once loaded keeps loading: renamed weights need a conversion-mapping rule, removed kwargs need a deprecation path, and a breaking change gets a 🚨 PR title and its own PR.
8. **Consistent public surface.** Same argument names, same output types across models β€” `pixel_values`, `input_ids`, `BaseModelOutput`, hidden states and attentions exposed the same way everywhere. This is enforced mechanically by the decorator stack and by the common tests; diverging names or a model whose `hidden_states` come back empty are violations.
## 1. Policy gate (before any code review)
- The work maps to an issue and there is coordination there (a maintainer or the issue author agreed to the approach). Link it.
- No open PR already does this: `gh pr list --repo huggingface/transformers --state open --search "<keywords>"`. If one exists and your approach differs materially, explain the difference on the issue first.
- The PR is not busywork (a single typo, one isolated lint fix). Bundle mechanical cleanups into a systematic scope, and not as a first contribution.
- If AI tools were used: the PR description says so and includes the coordination link, the differentiation from existing PRs, and the test commands with their results.
If any of these fails, stop β€” fix the coordination, not the code.
### The bug must exist
Maintainers now receive a steady stream of agent-written fixes for *theoretical* bugs: the pattern looks wrong, the fix looks sensible, and nobody has ever hit it. These PRs cost a review round each and add up to more maintainer time than real bugs do. Before opening any bugfix PR:
- A fix needs a **demonstrated failure**: a user report, a failing test, or an MRE (section 9) that triggers on a released checkpoint or a configuration people actually use. "This code path would misbehave if..." is not a bug β€” it is a hypothesis.
- If the trigger requires a config combination no published checkpoint uses and no user has reported, do not open the PR. If you believe it still matters, file an issue with the MRE and let a maintainer decide whether it warrants a patch β€” that costs them one minute instead of a review cycle.
- Pattern extrapolation is where agents go wrong: a real fix in one model does **not** imply the sibling models sharing the pattern are broken. Context differs β€” a guard that is dead in one model is load-bearing in another. If you want to propagate a fix, verify *per model* that the failure reproduces there on a real checkpoint, and coordinate on an issue before opening a sweep PR.
- Never let an agent write the "I have reviewed this PR" disclaimer. The disclosure and the section-14 report are the human's own statement; an auto-generated claim of human review is a policy violation, and maintainers recognize it.
## 2. Environment and ground rules
Your checkout is the source of truth, not your memory and not your assistant's training data.
```bash
PYTHONPATH=src python -c "import transformers; print(transformers.__file__)"
```
must print a path inside your checkout; prefix every python command below with `PYTHONPATH=src` otherwise. A test that silently imported the pip-installed transformers proves nothing about your branch.
Before citing or inheriting from any class, helper, or decorator, grep for it β€” the API moves fast and a symbol that existed six months ago may be gone or renamed (v5 removed head masking, head pruning, relative position biases in Bert-likes, TensorFlow/Jax, torchscript and torch.fx paths β€” see [MIGRATION_GUIDE_V5.md](MIGRATION_GUIDE_V5.md); do not reintroduce any of them):
```bash
grep -rn "<symbol>" src/transformers/ --include="*.py" | head
```
When unsure of a current idiom, open a recently merged model and copy what it does:
```bash
git log --diff-filter=A --name-only -- 'src/transformers/models/*/modular_*.py' | head
```
Three hard rules: never edit a generated file (`modeling_*.py` / `configuration_*.py` that has a `modular_*.py` next to it β€” edit the modular and regenerate); never edit code under a `# Copied from` comment without updating its source; never modify an existing model to make inheritance work for your new one.
## 3. Scope the diff
```bash
git diff main...HEAD # use your target branch if not main
git diff main...HEAD --name-only
```
Review the **whole** diff β€” code, tests, docs, scripts. If the branch trails `main` and the diff looks polluted with unrelated merged files, scope to your own commits: `git log main..HEAD --oneline`, then `git show <commit>` per commit. Every file in the final list must be one you can explain; stray debug scripts, notebooks, and generated artifacts come out before review, not after.
## 4. Modular structure
New or refactored models are authored in `src/transformers/models/<name>/modular_<name>.py`; everything else is generated. The full guide is [docs/source/en/modular_transformers.md](docs/source/en/modular_transformers.md) β€” the essentials and the traps:
- Every class inherits from the closest existing implementation, cross-family if needed: `class XAttention(LlamaAttention): pass` is the most common line in real modular files, and one modular file routinely pulls parents from four unrelated model families. A modular file that is mostly bare `nn.Module` definitions means the parent search was not done β€” grep distinctive identifiers (`layer_scale`, `q_norm`, gating patterns, codebook ops) across `src/transformers/models/` before writing anything from scratch, and check the parent table in the modular guide (MoE β†’ Mixtral/Qwen2-MoE, sliding window β†’ Gemma2/Cohere2, QK norm β†’ Olmo2/Cohere, SSM β†’ Mamba2/Bamba, …).
- "The architecture is novel" is not a waiver: novelty raises the bar for *how* conventions are applied, never *whether* they apply.
- The converter's grammar, in one paragraph: `pass` copies the parent verbatim with renames. `super().__init__(...)` copies the parent body and appends your lines β€” reassigning an attribute after it is the standard way to swap a submodule. `del self.attribute` removes the assignment (but not other references β€” override methods that still read it). Config classes remove inherited fields with `removed_attr = AttributeError()`. A method is deleted by overriding it with `raise AttributeError("...")`. `**super_kwargs` inherits a full signature for docstring-only overrides. One class-name prefix for the whole file (multimodal qualifiers like `<Name>Text` need explicit `pass` subclasses), `logger = logging.get_logger(__name__)` and a complete `__all__` at module level.
- RoPE or attention that *looks* different from an existing one is usually the same math up to a fixed weight permutation β€” inherit the existing class and absorb the layout difference in a load-time conversion (`PermuteForRope`, `Chunk` β€” see [src/transformers/core_model_loading.py](src/transformers/core_model_loading.py)). Verify the permutation standalone in float64 before trusting it. Never write a bespoke rotary because the reference's parameterization looks unfamiliar.
- When porting from a research repo, delete its experimental flags and ablation branches entirely β€” but keep the standard transformers training surface (`labels`, loss computation, gradient checkpointing). Transformers models train; reference-repo experiment scaffolding does not ship.
- Regenerate and check sync β€” this must exit 0:
```bash
PYTHONPATH=src python utils/modular_model_converter.py <name>
PYTHONPATH=src python utils/check_modular_conversion.py --files src/transformers/models/<name>/modular_<name>.py
```
- Read the generated file once in full: your prefix on every class, no cross-model imports surviving in it (the converter inlines parents), no leftover parent semantics that do not apply to your model.
## 5. v5 API conformance
The v5 surface is documented in [MIGRATION_GUIDE_V5.md](MIGRATION_GUIDE_V5.md); these are the points reviews reject most often.
**Output plumbing is owned by decorators.** No `output_attentions`, `output_hidden_states`, or `return_dict` in any forward signature, no manual collection loops, and no manual defaulting (`x = x if x is not None else self.config.x` β€” `@merge_with_config_defaults` owns that). Forwards take `**kwargs: Unpack[TransformersKwargs]`. The `PreTrainedModel` subclass declares `_can_record_outputs` mapping output keys to **class references, never strings** β€” a list when several classes produce one stream. Encoder forwards that produce the captured stream carry `@merge_with_config_defaults` + `@capture_outputs`; head forwards returning a `ModelOutput` carry `@can_return_tuple` + `@auto_docstring`. Never stack `@capture_outputs` with `@can_return_tuple` on one forward, and never put `@capture_outputs` on two levels of one call chain β€” the inner capture silently empties the outer one. Attention modules return `attn_output, attn_weights` unconditionally (no `if not output_attentions` guard), and layers are called with hidden states as the first *positional* argument (the capture hook reads `args[0]`).
**Attention goes through the interface.** One attention class per shape, dispatching via:
```python
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
self.config._attn_implementation, eager_attention_forward
)
```
No hand-rolled `if self.config._attn_implementation == "sdpa":` branches, no vendored eager/FA2/SDPA class triplets, no `*_ATTENTION_CLASSES` dicts. If your reference code casts dtypes per backend, the cast belongs at the call site around the single interface call β€” and check whether it is needed at all at the precision your parity tests run (at fp32, dtype casts are no-ops; the branches they justify are pure debt).
**Capability flags must match the implementation.** `_supports_sdpa` / `_supports_flash_attn` / `_supports_flex_attn` / `_can_compile_fullgraph` / `_supports_gradient_checkpointing` are claims, not decoration. A flag set `True` without the matching code path does not error β€” it silently no-ops or silently mis-runs, which is worse: gradient checkpointing that never checkpoints, a compile promise that graph-breaks. Each flag you set gets one verification run (section 11 for compile; a training step with checkpointing on for `_supports_gradient_checkpointing`).
**Configs are dataclass-style.** Class-level annotated fields with defaults, no `__init__`, `__post_init__` for derived values and backward-compatibility logic, `@auto_docstring` + `@strict` on every config class (they are not inherited β€” declare them on each). Rotary settings live in `config.rope_parameters` (a dict, nested per layer type when needed) β€” a bare `rope_theta` field is the v4 format. Composite models declare `sub_configs` and one sub-config per submodel with its own `model_type` and `base_config_key`; access nested values through the sub-config (`config.text_config.vocab_size`). Non-generative models have no `generation_config`. Every field must be read by something and every config-gated branch must be exercised by a released checkpoint β€” dead fields and dead `else` branches are findings (section 12). Architecture knobs are config fields, not constructor defaults, call-site literals, or hardcoded constants in the modeling file. Modules take `config`, not loose scalar dims.
**Weights.** `_tied_weights_keys` is a dict (`{"lm_head.weight": "model.embed_tokens.weight"}`). `_init_weights` covers **every** parameter your model adds β€” custom tokens, layer-scale lambdas, modality embeddings, non-persistent buffers β€” using the checkpoint-aware `init.*` primitives (`from ... import initialization as init`), never raw `nn.init`, and never `torch.empty` for a parameter default (use `torch.zeros`/`torch.ones` so the constructor value is defined). Delegate the standard cases first (`PreTrainedModel._init_weights(self, module)`) and branch only for the special ones. The trap: `from_pretrained` uses meta-device init that does *not* re-run `__init__`, so a parameter missing from both the checkpoint and `_init_weights` loads as uninitialized memory β€” silently, since the constructor default never materializes. Prove your coverage with the MRE pattern in section 9.
**Reuse generic infrastructure.** `GradientCheckpointingLayer` for transformer blocks; `GenericForSequenceClassification` / `GenericForTokenClassification` / `GenericForQuestionAnswering` for standard heads; `get_image_features` / `get_placeholder_mask` / `masked_scatter` for the VLM path (no per-image Python loops, no start/end-token surgery); the `EmbeddingAccessMixin` attribute (`_input_embed_layer`) instead of `get_input_embeddings` overrides; standard `generate` instead of bespoke inference methods. `get_*_features` helpers return a `BaseModelOutputWithPooling`, not a bare tensor.
**Dependencies.** No `einops` β€” rewrite with native `reshape`/`permute`/`unflatten`. No `torch.einsum` in modeling or processing hot paths (backend-dependent accumulation order breaks parity tests) β€” use explicit `@` / broadcasting. A genuinely unavoidable optional dependency is gated with `is_<dep>_available()` + `requires_backends`, never a bare import.
**Tokenizers.** One file per model on the named backends (`TokenizersBackend` preferred, `SentencePieceBackend` / `PythonBackend` as fallbacks); no slow/fast pairs, no `special_tokens_map.json` / `added_tokens.json`, `decode` handles batches (`batch_decode` is gone), `encode_plus` is `__call__`.
## 6. Processing
- Image/video processors sit on the named backends (`TorchvisionBackend` / `PilBackend`); the default `image_processing_<name>.py` is torchvision, the PIL variant is `image_processing_pil_<name>.py`. Override `_preprocess`, not `preprocess`, so the base class resolves kwarg defaults and your processor honors runtime `rescale_factor`/`image_mean`/`image_std`. No numpy in per-pixel paths, no `use_fast` (that is `backend=` now).
- `FeatureExtractor` classes no longer exist for vision; kwargs classes are shared (`XImageProcessorKwargs`, no `Fast` variant).
- Multimodal processors use the generic `ProcessorMixin` flow; prompt construction, conversation handling, and placeholder-token expansion live in `processing_<name>.py` and the chat template β€” never inside the model class. Stopping criteria, streaming, and image loading are owned by `generate` and the processor stack; delete them from ported reference code.
- `model_input_names` lists every emitted key. Class-default attributes must be JSON-native (`[2, 2]`, not `(2, 2)`) or save/load round-trips fail dict equality.
## 7. Checkpoint loading and conversion
The v5 loading stack ([src/transformers/core_model_loading.py](src/transformers/core_model_loading.py)) applies declarative transforms at load time, so `from_pretrained` can consume upstream checkpoints directly. The per-architecture registry is [src/transformers/conversion_mapping.py](src/transformers/conversion_mapping.py).
- Prefer a registry entry over a conversion script when the delta is renames/splits/merges β€” one mapping line can replace an entire duplicated architecture. A rename is a `WeightRenaming("attention.output.dense", "attention.o_proj")`; a structural change is a `WeightConverter` with ops:
```python
WeightConverter(
["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"],
"self_attn.qkv_proj",
operations=[Concatenate(dim=0)],
)
```
and the reverse direction (`Chunk` to split a fused tensor, `PermuteForRope` for rotary layout changes) works the same way. An architecture that matches an existing mapping up to renames gets an alias line in `_MODEL_TO_CONVERSION_PATTERN` instead of a copied block.
- Conversions must be **reversible**: loading then saving must round-trip to the same checkpoint. `test_reverse_loading_mapping` checks this; a skip on that test is a coverage gap, not a pass. Keep converters leaf-scoped (`"wqkv.weight"` β†’ `["q_proj.weight", ...]`) and let renamings handle prefixes β€” full-path converters with regex backrefs in their targets do not reverse.
- Always load with `strict=True` during development and **read the load report**: a clean load (no MISSING / no UNEXPECTED keys) is half the parity proof. A MISSING q/k/v + UNEXPECTED fused-weight pair means your conversion silently no-oped and the layer is running on random init β€” the model then produces garbage that still has the right shape. Never loosen to non-strict to make a load pass.
- Verify the final parity through `from_pretrained` on the real checkpoint directory, not only a manual `load_state_dict` β€” the two paths initialize buffers differently (see the `_init_weights` trap above), and only `from_pretrained` exercises your conversion entries.
## 8. Numerical parity (the non-negotiable)
Integration tests compare **numbers**, never shapes. The ladder:
1. Tiny-config forward runs (CPU, random init), exercising the full path β€” for multimodal, `input_ids` + `pixel_values` with correctly counted placeholder tokens, not just the text tower.
2. Same weights + same seeded input through your port and the reference implementation, `torch.allclose` at fp32: noise is ~1e-5; a ~1e-2 gap is a real divergence (norm order, RoPE parameterization, wrong slice) β€” find it, **never widen the tolerance to make it pass**. Across devices, 100% argmax agreement plus matching top-5 is the bar.
3. Integration tests pin expected slices (logits, hidden states, boxes, decoded text) produced by the verified parity run, with a comment stating where the values come from β€” a reproducible command, not a reference to a file that is not in the repo. Device-dependent expectations use the `Expectations` helper (per-device value dicts), not widened tolerances. Checkpoint-dependent tests are marked `@slow` and must pass under `RUN_SLOW=1`.
4. Reproduce the reference's arithmetic exactly where weights were trained against it (cast order, fp32 boundaries, the exact `x * sigmoid(x)` form). A one-line dtype difference is an architecture delta to port, not noise to tolerate. Every cast you add or remove relative to the reference needs stated parity evidence.
Tests use the common mixins (`ModelTesterMixin`, `ImageProcessingTestMixin`, `ProcessorTesterMixin`) β€” a hand-rolled `unittest.TestCase` with a few asserts is not coverage. Every `@unittest.skip` names a concrete blocker; "flaky" or "not needed" is not a blocker. Every bugfix ships the test that reproduces it.
### When outputs don't match: pitfalls to consult
Not a checklist β€” most won't apply to any given model. Consult when your port diverges from the reference and the cause isn't obvious:
- **Small diffs feeding an iterative process are not small.** A ~1e-3 per-token logit diff looks dismissible, but `generate` argmaxes at every step: one flipped token early in decoding cascades into a completely different sequence. Check whether a precision diff feeds argmax/sampling before accepting it.
- **Position and timestep dtypes.** RoPE cos/sin values are sensitive to the dtype of the *position* coordinates, not just q/k. If the reference computes positions in a different dtype (or int vs float), the rotation diverges.
- **Config values are what the checkpoint says, not what the code defaults say.** The published `config.json` may override every default you assumed. Read the actual config before reasoning about which branches run.
- **RNG provenance.** Reference scripts often rely on the global RNG (`torch.manual_seed`) where your harness passes a `generator=` β€” or vice versa. Match the mechanism, not just the seed.
- **Cast boundaries.** `noise/activations generated in fp32 then cast to bf16` is different from `generated in bf16` β€” the quantization happens at a different point. Match where the reference casts, not just what it casts to.
- **The comparison harness itself.** Same device, same dtype, same attention backend, eval mode, no dropout, deterministic input. Half of "parity failures" are harness asymmetries.
## 9. Prove it with an MRE
Any claim of the form "this breaks under X", "this loads wrong", "this shifts silently" β€” in your PR description, in a review reply, or in your own head β€” is settled by a **minimal reproducible example**, not by prose. The rules:
- Self-contained: runs against the current tree on a laptop, no hub downloads, no GPU, no real datasets. Construct the failing object directly β€” a tiny config, zero tensors, a saved-and-reloaded local checkpoint.
- Ends in a `print(...)` or `assert ...` that materializes the failure (wrong value, shifted tuple, shape mismatch, raised exception). The reader runs it and sees the bug.
- Under ~25 lines; longer means it is two claims β€” split it.
Example β€” proving `_init_weights` coverage for a new parameter (the section-5 trap):
```python
import torch
from transformers import MyConfig, MyModel
common = dict(hidden_size=32, num_hidden_layers=2, num_attention_heads=2, intermediate_size=64)
MyModel(MyConfig(**common)).save_pretrained("/tmp/tiny") # checkpoint WITHOUT the new keys
config_new = MyConfig(use_my_new_embedding=True, **common) # config that CREATES them
model = MyModel.from_pretrained("/tmp/tiny", config=config_new) # missing-key init path
assert (model.my_new_embedding == 0).all(), "not zero-initialized" # whatever the ctor specifies
```
If this assert fails on your branch, the parameter loads as uninitialized memory for every user who warm-starts from an older checkpoint β€” a bug no shape test and no fp32 parity test will ever catch. The same pattern proves the opposite direction after you fix it. Ship the MRE-derived test with the fix.
## 10. torch.compile
If you touched a `forward`, run it compiled before claiming it works:
```python
import torch, torch._dynamo as dynamo
model = YourModel(tiny_config).eval()
explained = dynamo.explain(model)(inputs)
print(explained.graph_break_count, [r.reason for r in explained.break_reasons])
torch.compile(model, fullgraph=True, backend="eager")(inputs)
```
Grep-level break patterns to remove from forwards: Python `if` on any tensor expression (including `and`/`or` chains β€” the comparison calls `.item()` implicitly), `.item()` / `.tolist()` / `.cpu()` / `.numpy()`, `range(tensor)`, `int(tensor)`, slicing with a tensor step, data-dependent loops. Restructure with masking, `torch.where`, or hoist the logic into processing / `_expand_inputs_for_generation`. Compare the break count against `main` β€” pre-existing breaks are not yours to fix, new ones are yours to remove. `torch.export` and `dynamo` are the supported compilation APIs; torchscript and torch.fx are gone.
Related portability rule: no `torch.float64` in modeling code β€” MPS, NPU, and similar backends error or silently fall back. Reference repos reach for float64 in RoPE frequency bases and positional precompute; fp32 is almost always sufficient at inference. Grep your diff for `float64` / `.double()` before review.
## 11. Backward compatibility
- Public APIs evolve additively. New config fields carry defaults that preserve existing checkpoint behavior β€” with all new flags off, the model must be **bit-identical** to before (test it, don't assert it).
- A renamed weight or changed key layout needs a [conversion_mapping.py](src/transformers/conversion_mapping.py) rule so old checkpoints keep loading β€” in both directions (section 7).
- A genuinely breaking change gets 🚨 in the PR title and its own PR β€” never rides along an unrelated diff. An opt-in feature must be bit-inert when the flag is unset.
- Removed kwargs break `Trainer` column passing and downstream callers; check callers before touching a public signature. Some signatures are load-bearing in non-obvious ways (a `labels` kwarg that only raises `NotImplementedError` still routes dataset columns).
## 12. Dead code and reachability (advisory)
For any new model or substantial new surface, trace how the code is actually reached from the user entrypoints β€” `from_pretrained` β†’ `forward` per task head, `generate` for generative models, the processor's `__call__` for processing:
1. **Trace the call path.** Follow every call from the entrypoint into your modules: which arguments are passed, which branches taken, which helpers invoked.
2. **Check reachability under released configs.** An `if self.config.use_foo:` branch where no published checkpoint sets `use_foo` is likely dead; so is a code path only reachable with argument combinations nothing produces.
3. **Flag unused weight.** Parameters declared in `forward` but never passed by any caller; private methods never called; layers initialized in `__init__` but never used in `forward` (these also pollute the checkpoint surface as loadable-but-dead weights).
4. **Qualify the findings.** Configs on the Hub can differ from code defaults, so frame it honestly: "under the default config and the traced call path, this appears unreachable." If you know the config that exercises it, say which; if you don't, remove it or ask in the PR.
Also sweep for **ephemeral context**: comments, docstrings, and files that only make sense to this PR's author or review thread β€” `# per reviewer comment`, `# as discussed`, debug printouts, parity harnesses with hardcoded local paths, comparison scripts against the reference repo. Either restate the *reason* so the comment stands alone for a future reader, or delete it. Working artifacts stay on your machine, not in the diff.
## 13. Docs impact and final sweep
A PR can leave existing docs stale or create surface that has none. Scan what your change touches:
- New or changed public behavior β€” a new model, a new argument, a changed default, a renamed API β€” needs matching updates in `docs/source/en/`, docstrings, and examples. Flag anything that now describes outdated behavior.
- New models: docs page + `docs/source/en/_toctree.yml` entry in the right modality section, auto-class registrations (`CONFIG_MAPPING_NAMES`, `modeling_auto.py`, processor/tokenizer mappings), complete `__all__`.
Then the mechanical gate:
```bash
make style
PYTHONPATH=src python utils/check_modular_conversion.py # if modular files touched
pytest tests/models/<name>/ -x
RUN_SLOW=1 pytest tests/models/<name>/test_modeling_<name>.py -k integration -x # if you have the hardware
```
## 14. Report
End the self-review with this report and paste it into the PR description. Findings are grouped by severity, each with a title, a one-sentence explanation, a `file.py:line`, and the impact; cite the rule or document it violates.
```text
--- Self-review: <branch> ---
POLICY: issue <link>, coordination <link>, AI assistance: <yes/no + tools>
TRIGGER (bugfix PRs): <user report / failing test / MRE on a released checkpoint β€” what actually exhibits the bug>
CHECKS RUN: modular sync | style | fast tests | slow tests <run/not run + why> | compile <break count vs main>
PARITY: <max abs diff at fp32 / argmax agreement / not applicable + why>
BLOCKING (fixed before submitting):
1. <title> β€” <file.py:line> β€” <what was wrong, rule cited, how fixed>
NON-BLOCKING (left for the reviewer):
1. <title> β€” <file.py:line> β€” <the judgment call and why you did not decide it alone>
DEAD CODE (advisory):
<path:line> | likely-dead / used | <reason, qualified per section 12>
KNOWN LIMITATIONS: <anything intentionally out of scope, stated plainly>
VERDICT: READY | NEEDS CHANGES
```
Two calibration rules borrowed from hard experience. First, **fix all blocking findings before submitting, but leave genuine judgment calls for the reviewer** β€” a non-blocking finding you are not sure about is raised in the report, not silently "fixed" by guessing; a wrong guess costs more review time than the question. Second, report outcomes faithfully: if a test fails, say so with the output; if a step was skipped, say that and why. A finding you found and fixed yourself costs nothing; the same finding found by a reviewer costs a round-trip week.