Debug SD.Next And Diffusers Model Port
Read the error, identify which integration layer is failing, isolate the smallest reproducible failure point, fix the root cause, and validate the fix without expanding scope.
When To Use
- A newly added SD.Next model type does not autodetect correctly
- The loader fails to instantiate a pipeline or component
- A custom pipeline imports but fails during
from_pretrained
- Prompt encoding fails because of tokenizer, processor, or text encoder mismatch
- Sampling fails due to tensor shape, dtype, device, or scheduler issues
- The model loads but outputs corrupted images, wrong output type, or obviously incorrect results
Guidance
- Consult
.github/instructions/core.instructions.md for relevant core runtime and model debugging guidance before proceeding.
Debugging Order
Always debug from the outside in.
- Integration entry checks: detection and routing.
- Load path checks: loader arguments and component selection, checkpoint path and artifact layout, then weight loading and key mapping.
- Runtime path checks: prompt encoding, sampling forward path, and output postprocessing plus SD.Next task integration.
Do not start by rewriting the architecture when the failure appears in detection, loader wiring, or output handling. Only consider architecture rewrites after these layers are validated and the root cause is confirmed to be architectural.
Files To Check First
.github/copilot-instructions.md
.github/instructions/core.instructions.md
modules/sd_detect.py
modules/sd_models.py
modules/modeldata.py
pipelines/model_<name>.py
pipelines/<model>/model.py
pipelines/<model>/pipeline.py
pipelines/generic.py
If the port is based on a standalone script, compare the failing path against the original reference implementation and identify the first semantic divergence.
Failure Classification
1. Model Not Detected Or Misclassified
Check:
- Filename and repo-name heuristics in
modules/sd_detect.py
- Loader dispatch branch in
modules/sd_models.py
- Reverse pipeline classification in
modules/modeldata.py
Typical symptoms:
- Wrong loader called
- Pipeline classified as a broader family such as
chroma instead of a custom zetachroma
- Task switching behaves incorrectly because the loaded pipeline type is wrong
2. Loader Fails Before Pipeline Construction
Check:
sd_models.path_to_repo(checkpoint_info) output
generic.load_transformer(...) and generic.load_text_encoder(...) arguments
- Duplicate kwargs such as
torch_dtype
- Wrong class chosen for text encoder, tokenizer, or processor
- Whether the source is really a Diffusers repo or only a raw checkpoint
Typical symptoms:
- Missing subfolder errors
from_pretrained argument mismatch
- Component class mismatch
3. Raw Checkpoint Load Fails
Check:
- Checkpoint path resolution for local file, local directory, and Hub repo
- State dict load method
- Key remapping logic
- Config inference from tensor shapes
- Missing versus unexpected keys after
load_state_dict
Typical symptoms:
- Key mismatch explosion
- Wrong inferred head counts, dimensions, or decoder settings
- Silent shape corruption caused by a bad remap
4. Prompt Encoding Fails
Check:
- Tokenizer or processor choice
trust_remote_code requirements
- Chat template or custom prompt formatting
- Hidden state index selection
- Padding and batch alignment between positive and negative prompts
Typical symptoms:
- Tokenizer attribute errors
- Hidden state shape mismatch
- CFG failures when negative prompts do not match prompt batch length
5. Sampling Or Forward Pass Fails
Check:
- Input tensor shape and channel count
- Device and dtype alignment across all components
- Scheduler timesteps and expected timestep convention
- Classifier-free guidance concatenation and split logic
- Pixel-space versus latent-space assumptions
Typical symptoms:
- Shape mismatch in attention or decoder blocks
- Device mismatch between text encoder output and model tensors
- Images exploding to NaNs because timestep semantics are inverted
6. Output Is Wrong But No Exception Is Raised
Check:
- Whether the model predicts
x0, noise, or velocity
- Whether the Euler or other sampler update matches the model objective
- Final scaling and clamp path
output_type handling and pipe.task_args
- Whether a VAE is being applied incorrectly to direct pixel-space output
Typical symptoms:
- Black, gray, washed-out, or heavily clipped images
- Output with correct size but obviously broken semantics
- Correct tensors but wrong SD.Next display behavior because output type is mismatched
Minimal Debug Procedure
1. Reproduce Narrowly
Capture the smallest failing operation.
- Pure import failure
- Loader-only failure
from_pretrained failure
- Prompt encode failure
- Single forward pass failure
- First sampler step failure
Prefer narrow Python checks before attempting a full generation run.
2. Compare Against Working Pattern
Find the closest working in-repo analogue and compare:
- Loader structure
- Registered module names
- Pipeline class name and module registration
- Prompt encoding path
- Output conversion path
3. Fix The Root Cause
Examples:
- Add the missing
modeldata branch instead of patching downstream task handling
- Fix checkpoint remapping rather than forcing
strict=False and ignoring real mismatches
- Correct the output path for pixel-space models instead of routing through a VAE
- Make config inference fail explicitly when ambiguous instead of guessing silently
4. Validate In Layers
After each meaningful fix, validate the narrowest relevant layer first.
compileall or syntax check
ruff on touched files
- Import smoke test
- Loader-only smoke test
- Full run only when the lower layers are stable
Common Root Causes
modules/modeldata.py not updated after adding a new custom pipeline family
modules/sd_detect.py branch order causes overbroad detection to win first
- Loader passes duplicated keyword args like
torch_dtype
- Shared text encoder assumptions do not match the actual model variant
from_pretrained assumes transformer/ or text_encoder/ subfolders that do not exist
- Key remapping merges QKV in the wrong order
- CFG path concatenates embeddings or latents incorrectly
- Direct pixel-space models are postprocessed like latent-space diffusion outputs
- Negative prompts are not padded or repeated to match prompt batch shape
- Pipeline class naming collides with broader family checks in
modeldata
Validation Checklist
When closing the task, report which of these were completed:
- Exact failing layer identified
- Root cause fixed
- Syntax check passed
- Focused lint passed
- Import or loader smoke test passed
- Real generation tested, or explicitly not tested
Example Request Shapes
- "The new model port fails in from_pretrained"
- "SD.Next detects my custom pipeline as the wrong model type"
- "The loader works but generation returns black images"
- "This standalone-script port loads weights but crashes in attention"
1---2name: debug-model3description: Debug a broken SD.Next or Diffusers model integration. Use when a newly added or ported model fails to load, misdetects, crashes during prompt encoding or sampling, or produces incorrect outputs.4---56# Debug SD.Next And Diffusers Model Port78Read the error, identify which integration layer is failing, isolate the smallest reproducible failure point, fix the root cause, and validate the fix without expanding scope.910## When To Use1112- A newly added SD.Next model type does not autodetect correctly13- The loader fails to instantiate a pipeline or component14- A custom pipeline imports but fails during `from_pretrained`15- Prompt encoding fails because of tokenizer, processor, or text encoder mismatch16- Sampling fails due to tensor shape, dtype, device, or scheduler issues17- The model loads but outputs corrupted images, wrong output type, or obviously incorrect results1819## Guidance2021- Consult `.github/instructions/core.instructions.md` for relevant core runtime and model debugging guidance before proceeding.2223## Debugging Order2425Always debug from the outside in.26271. Integration entry checks: detection and routing.282. Load path checks: loader arguments and component selection, checkpoint path and artifact layout, then weight loading and key mapping.293. Runtime path checks: prompt encoding, sampling forward path, and output postprocessing plus SD.Next task integration.3031Do not start by rewriting the architecture when the failure appears in detection, loader wiring, or output handling. Only consider architecture rewrites after these layers are validated and the root cause is confirmed to be architectural.3233## Files To Check First3435- `.github/copilot-instructions.md`36- `.github/instructions/core.instructions.md`37- `modules/sd_detect.py`38- `modules/sd_models.py`39- `modules/modeldata.py`40- `pipelines/model_<name>.py`41- `pipelines/<model>/model.py`42- `pipelines/<model>/pipeline.py`43- `pipelines/generic.py`4445If the port is based on a standalone script, compare the failing path against the original reference implementation and identify the first semantic divergence.4647## Failure Classification4849### 1. Model Not Detected Or Misclassified5051Check:5253- Filename and repo-name heuristics in `modules/sd_detect.py`54- Loader dispatch branch in `modules/sd_models.py`55- Reverse pipeline classification in `modules/modeldata.py`5657Typical symptoms:5859- Wrong loader called60- Pipeline classified as a broader family such as `chroma` instead of a custom `zetachroma`61- Task switching behaves incorrectly because the loaded pipeline type is wrong6263### 2. Loader Fails Before Pipeline Construction6465Check:6667- `sd_models.path_to_repo(checkpoint_info)` output68- `generic.load_transformer(...)` and `generic.load_text_encoder(...)` arguments69- Duplicate kwargs such as `torch_dtype`70- Wrong class chosen for text encoder, tokenizer, or processor71- Whether the source is really a Diffusers repo or only a raw checkpoint7273Typical symptoms:7475- Missing subfolder errors76- `from_pretrained` argument mismatch77- Component class mismatch7879### 3. Raw Checkpoint Load Fails8081Check:8283- Checkpoint path resolution for local file, local directory, and Hub repo84- State dict load method85- Key remapping logic86- Config inference from tensor shapes87- Missing versus unexpected keys after `load_state_dict`8889Typical symptoms:9091- Key mismatch explosion92- Wrong inferred head counts, dimensions, or decoder settings93- Silent shape corruption caused by a bad remap9495### 4. Prompt Encoding Fails9697Check:9899- Tokenizer or processor choice100- `trust_remote_code` requirements101- Chat template or custom prompt formatting102- Hidden state index selection103- Padding and batch alignment between positive and negative prompts104105Typical symptoms:106107- Tokenizer attribute errors108- Hidden state shape mismatch109- CFG failures when negative prompts do not match prompt batch length110111### 5. Sampling Or Forward Pass Fails112113Check:114115- Input tensor shape and channel count116- Device and dtype alignment across all components117- Scheduler timesteps and expected timestep convention118- Classifier-free guidance concatenation and split logic119- Pixel-space versus latent-space assumptions120121Typical symptoms:122123- Shape mismatch in attention or decoder blocks124- Device mismatch between text encoder output and model tensors125- Images exploding to NaNs because timestep semantics are inverted126127### 6. Output Is Wrong But No Exception Is Raised128129Check:130131- Whether the model predicts `x0`, noise, or velocity132- Whether the Euler or other sampler update matches the model objective133- Final scaling and clamp path134- `output_type` handling and `pipe.task_args`135- Whether a VAE is being applied incorrectly to direct pixel-space output136137Typical symptoms:138139- Black, gray, washed-out, or heavily clipped images140- Output with correct size but obviously broken semantics141- Correct tensors but wrong SD.Next display behavior because output type is mismatched142143## Minimal Debug Procedure144145### 1. Reproduce Narrowly146147Capture the smallest failing operation.148149- Pure import failure150- Loader-only failure151- `from_pretrained` failure152- Prompt encode failure153- Single forward pass failure154- First sampler step failure155156Prefer narrow Python checks before attempting a full generation run.157158### 2. Compare Against Working Pattern159160Find the closest working in-repo analogue and compare:161162- Loader structure163- Registered module names164- Pipeline class name and module registration165- Prompt encoding path166- Output conversion path167168### 3. Fix The Root Cause169170Examples:171172- Add the missing `modeldata` branch instead of patching downstream task handling173- Fix checkpoint remapping rather than forcing `strict=False` and ignoring real mismatches174- Correct the output path for pixel-space models instead of routing through a VAE175- Make config inference fail explicitly when ambiguous instead of guessing silently176177### 4. Validate In Layers178179After each meaningful fix, validate the narrowest relevant layer first.180181- `compileall` or syntax check182- `ruff` on touched files183- Import smoke test184- Loader-only smoke test185- Full run only when the lower layers are stable186187## Common Root Causes188189- `modules/modeldata.py` not updated after adding a new custom pipeline family190- `modules/sd_detect.py` branch order causes overbroad detection to win first191- Loader passes duplicated keyword args like `torch_dtype`192- Shared text encoder assumptions do not match the actual model variant193- `from_pretrained` assumes `transformer/` or `text_encoder/` subfolders that do not exist194- Key remapping merges QKV in the wrong order195- CFG path concatenates embeddings or latents incorrectly196- Direct pixel-space models are postprocessed like latent-space diffusion outputs197- Negative prompts are not padded or repeated to match prompt batch shape198- Pipeline class naming collides with broader family checks in `modeldata`199200## Validation Checklist201202When closing the task, report which of these were completed:2032041. Exact failing layer identified2052. Root cause fixed2063. Syntax check passed2074. Focused lint passed2085. Import or loader smoke test passed2096. Real generation tested, or explicitly not tested210211## Example Request Shapes212213- "The new model port fails in from_pretrained"214- "SD.Next detects my custom pipeline as the wrong model type"215- "The loader works but generation returns black images"216- "This standalone-script port loads weights but crashes in attention"