14 KiB
CWB Model Graft
CWB Model Graft (CWBModelGraft) is a standalone training-free diffusion model grafting node that transfers selected blocks, operator families, projection sub-slices, or explicitly mapped layers from a donor diffusion model (model_b) into a base diffusion model (model_a) using Consensus-Weighted Blending (CWB).
model_a defines the output architecture, tensor key set, output shapes, and safetensors metadata. Tensors that are protected, excluded by block or sub-part rules, or absent from model_b are preserved from model_a without modification.
End-to-End Execution Pipeline
For every logical tensor key in model_a, CWB Model Graft executes the following sequence:
-
Quantization & Low-Bit Inspection
- Both
model_aandmodel_bare opened withMemoryEfficientSafeOpenand inspected viaDiffusionQuantizationanddiffusion_key_map. - Full-model ComfyUI/comfy-kitchen quantized files or files containing 3 or more bare low-bit (
INT8,UINT8,FP8,FP4) tensors are rejected before opening an output writer. - Any layer with 1–2 isolated low-bit tensors in either
model_aor the resolvedmodel_bsource keys is preserved byte-for-byte frommodel_a(force_raw=True).
- Both
-
Discard & Exclude / Include Pattern Filtering
discard_patterns: If amodel_akey (or its physical key) matchesdiscard_patterns, the tensor is omitted from the output file.exclude_patternswithinclude_mode = False(default): Matching keys are preserved unchanged frommodel_a.exclude_patternswithinclude_mode = True: Acts as a whitelist. Non-matching keys are preserved unchanged frommodel_a. Explicitly matched whitelist keys are eligible for grafting even if they lie outside standard block numbering (such astext_embedderor modulation layers).
-
Donor Key Resolution & Automatic QKV Packing / Splitting
- Custom Key Map (
custom_key_map): Checked first. Ifbase_keyhas an explicit mappingdonor_key -> base_keyanddonor_keyexists inmodel_b,donor_keyis used as the donor source. - Direct Match: If
base_keyexists directly inmodel_b, it is paired 1-to-1. - Split-to-Fused QKV (
fuse_qkv): Ifmodel_ahas a fused<prefix>.proj.qkv.weighttensor andmodel_binstead stores split<prefix>.proj.q.weight,<prefix>.proj.k.weight, and<prefix>.proj.v.weight, all three donor tensors are streamed in the same work unit and concatenated alongdim=0(torch.cat([q, k, v], dim=0)) before sub-part selection and CWB blending. - Fused-to-Split QKV (
split_qkv): Ifmodel_ahas split<prefix>.proj.{q,k,v}.weightandmodel_bstores fused<prefix>.proj.qkv.weight, the fused donor tensor is streamed and split into 3 equal chunks alongdim=0(chunk(3, dim=0)), selecting index0forq,1fork, or2forv. - Unmatched Keys: If no donor source exists for
base_key,model_a's tensor is preserved unchanged.
- Custom Key Map (
-
Block Index Detection & Early-Block Protection
- Main transformer block indices are parsed from keys matching
(^|\.)(layers|blocks|double_blocks|single_blocks|transformer_blocks)\.(\d+)\.. - Auxiliary sub-networks (
text_embedder.*,token_refiner.*) do not count toward main transformer block numbering and are preserved frommodel_aunless targeted viacustom_key_maporinclude_mode=Truewithexclude_patterns. max_block_indexis computed as the highest main block index inmodel_a.- If a key's
block_idx < protect_early_blocks, the tensor is preserved 100% frommodel_a.
- Main transformer block indices are parsed from keys matching
-
Operator Classification & Block Scheduling
- Each main-block key is classified by its token path:
- Attention (
attention):.qkv.,.qkv_proj.,.proj.q.,.proj.k.,.proj.v.,.proj.o.,.attn.,.self_attn.,.q_norm.,.k_norm.,.to_q.,.to_k.,.to_v.,.to_out.. - Feed-Forward (
ffn):.ffn_up_gate.,.ffn_up.,.ffn_gate.,.ffn_down.,.mlp.,.ff.,.fc1.,.fc2.,.w1.,.w2.,.w3..
- Attention (
- Keys inside main blocks that are neither attention nor feed-forward (such as block-level
norm1andnorm2) are preserved frommodel_aunless explicitly targeted viacustom_key_maporinclude_mode=True. - For classified keys with
block_idx >= protect_early_blocks, the corresponding rule (attention_block_ruleorffn_block_rule) determines whether the block is grafted:all_after_protected: Every block withblock_idx >= protect_early_blocks.interleaved_even: Even-numbered blocks (block_idx % 2 == 0) withblock_idx >= protect_early_blocks.interleaved_odd: Odd-numbered blocks (block_idx % 2 == 1) withblock_idx >= protect_early_blocks.back_half_only: Blocks in the second half of the network (block_idx >= max(protect_early_blocks, (max_block_index + 1) // 2)).none: No blocks of this operator family are grafted.
- Each main-block key is classified by its token path:
-
Sub-Part Slicing (
attention_subpartandffn_subpart)- Attention Sub-Parts (
attention_subpart):all: All attention tensors in selected blocks (qkv,q,k,v,o,q_norm,k_norm) are grafted.value_and_output:- Split query/key projections and norms (
.proj.q.,.proj.k.,.to_q.,.to_k.,.q_norm.,.k_norm.) are preserved 100% frommodel_a. - Fused QKV weights (
.qkv.,.qkv_proj.) whose first dimension is divisible by 3 are split intoq_a, k_a, v_a = base.chunk(3, dim=0)andq_b, k_b, v_b = donor.chunk(3, dim=0).q_aandk_aare kept byte-exact frommodel_a,v_aandv_bare CWB-blended intov_merged, and the tensor is reassembled astorch.cat([q_a, k_a, v_merged], dim=0). - Split value projections (
.proj.v.,.to_v.) and output projections (.proj.o.,.out_proj.,.to_out.) are CWB-blended in full.
- Split query/key projections and norms (
output_only: Only attention output projections (.proj.o.,.out_proj.,.to_out.) are CWB-blended; all Q/K/V and norm tensors are preserved 100% frommodel_a.
- Feed-Forward Sub-Parts (
ffn_subpart):all: All feed-forward tensors in selected blocks (ffn_up_gate,ffn_up,ffn_gate,ffn_down,fc1,fc2,w1,w2,w3) are grafted.up_only:- Down and gate projections (
.ffn_down.,.fc2.,.w2.,.ff.net.2.,.ffn_gate.,.w3.) are preserved 100% frommodel_a. - Fused up+gate weights (
.ffn_up_gate.) whose first dimension is divisible by 2 are split intoup_a, gate_a = base.chunk(2, dim=0)andup_b, gate_b = donor.chunk(2, dim=0). Onlyup_aandup_bare CWB-blended intoup_merged,gate_ais preserved 100% frommodel_a, and the tensor is reassembled astorch.cat([up_merged, gate_a], dim=0). - Split up projections (
.ffn_up.,.fc1.,.w1.) are CWB-blended in full.
- Down and gate projections (
down_only: Only down projections (.ffn_down.,.fc2.,.w2.,.ff.net.2.) are CWB-blended; all up/gate tensors are preserved 100% frommodel_a.
- Attention Sub-Parts (
-
Cross-Shape Alignment, Row Similarity Matching & Norm Locking
- Trailing-Dimension Alignment: If
donor_tensorandbase_tensordiffer in shape:- Same element count with different rank:
donor_tensoris reshaped tobase_tensor.shape. - Different rank and different element count:
donor_tensoris linearly interpolated in FP32 tobase_tensor.numel()and reshaped tobase_tensor.shape. - Same rank (
ndim >= 2) with different trailing dimensions (donor_tensor.shape[1:] != base_tensor.shape[1:]): Each donor row is linearly interpolated in FP32 along its flattened trailing features to matchprod(base_tensor.shape[1:])and reshaped to(donor_rows, *base_tensor.shape[1:]).
- Same element count with different rank:
- Row Matching & CWB Blending:
merge_cwb_tensorsruns in FP32 withallow_similarity_alignment=Trueandreference_index=0(model_aas reference). When the active CWB settings usealignment_method="similarity"(or when row counts differ), donor rows are greedily paired to base rows by cosine similarity (subject toalignment_thresholdandposition_weight). Unmatched base rows remain anchored tomodel_a. - Base Magnitude Locking: Whenever
donor_tensorrequired shape alignment orrescale_normis enabled in the active CWB settings, the blended tensor's overall Frobenius norm is locked tomodel_a's tensor norm (merged * (||base|| / ||merged||)), preventing activation scale drift across downstream blocks.
- Trailing-Dimension Alignment: If
-
Atomic Streaming Output & Metadata
- Tensors are streamed one work unit at a time through UEL (
batch_size=1,prefetch_batches=1), written incrementally viaatomic_uel_writer, and released before advancing to the next layer. - If a CUDA out-of-memory error occurs on a layer, the failed GPU working set is released and that layer retries on CPU.
- Output metadata preserves
model_a's metadata and records a JSON summary undercwb.graftcontainingbase_model,donor_model,attention_preset,ffn_preset,protect_early_blocks,attention_block_rule,ffn_block_rule,attention_subpart, andffn_subpart.
- Tensors are streamed one work unit at a time through UEL (
Complete Input Reference
execution_mode(MERGE|DOCUMENTATION ONLY, defaultMERGE):MERGE: Executes the streaming graft and writes the output.safetensorsfile undermodels/diffusion_models/.DOCUMENTATION ONLY: Returns this documentation string without opening any model files.
model_a(Combo,diffusion_models):- Base diffusion model that anchors architecture, output tensor keys, shapes, metadata, and untouched/protected layers.
model_b(Combo,diffusion_models):- Donor diffusion model from which selected blocks, sub-projections, or mapped layers are grafted into
model_a.
- Donor diffusion model from which selected blocks, sub-projections, or mapped layers are grafted into
attention_preset(Combo, defaultrobust_medn):- Dense CWB preset applied to grafted attention tensors (
balanced_mean,robust_medn,selective_mean,varied_mean_rn_softcb,diverse_medn_rn_dsc_softcb,strongdiv_medn_rn_dsc_softcb). Overridden completely ifattention_configis connected.
- Dense CWB preset applied to grafted attention tensors (
attention_config(CWB_CONFIG, optional):- Optional custom CWB configuration from
CWB Custom Configurationfor attention layers. Enablingalignment_method = "similarity"on this config activates greedy cosine row matching across attention rows.
- Optional custom CWB configuration from
ffn_preset(Combo, defaultbalanced_mean):- Dense CWB preset applied to grafted feed-forward (MLP) tensors and custom-mapped non-attention tensors. Overridden completely if
ffn_configis connected.
- Dense CWB preset applied to grafted feed-forward (MLP) tensors and custom-mapped non-attention tensors. Overridden completely if
ffn_config(CWB_CONFIG, optional):- Optional custom CWB configuration from
CWB Custom Configurationfor feed-forward (MLP) layers.
- Optional custom CWB configuration from
protect_early_blocks(Int, default2, range0..256):- Number of initial main transformer blocks (
0 .. protect_early_blocks - 1) kept 100% identical tomodel_aso global image composition and layout remain stable.
- Number of initial main transformer blocks (
attention_block_rule(interleaved_even|interleaved_odd|back_half_only|all_after_protected|none, defaultinterleaved_even):- Block selection schedule for attention layers at index
>= protect_early_blocks.
- Block selection schedule for attention layers at index
ffn_block_rule(all_after_protected|interleaved_even|interleaved_odd|back_half_only|none, defaultall_after_protected):- Block selection schedule for feed-forward (MLP) layers at index
>= protect_early_blocks.
- Block selection schedule for feed-forward (MLP) layers at index
attention_subpart(all|value_and_output|output_only, defaultall):- Restricts attention grafting to all attention weights, only the Value (
V) slice/projection and Output (O) projection, or only the Output (O) projection.
- Restricts attention grafting to all attention weights, only the Value (
ffn_subpart(all|up_only|down_only, defaultall):- Restricts feed-forward grafting to all FFN weights, only the Up projection (including the
uphalf of packedffn_up_gate), or only the Down projection.
- Restricts feed-forward grafting to all FFN weights, only the Up projection (including the
custom_key_map(String, multiline, default""):- Optional explicit key mappings, one per line, formatted as
donor_key -> base_keyordonor_key = base_key(lines starting with#are ignored). Mapped keys bypass block-number filtering so arbitrary donor tensors can be grafted into specific base tensors.
- Optional explicit key mappings, one per line, formatted as
output_filename(String, defaultcwb_grafted_model):- Output filename relative to
models/diffusion_models/(.safetensorsextension added automatically).
- Output filename relative to
save_dtype(fp32|fp16|bf16, defaultbf16):- Target floating-point precision when
override_dtypeis enabled or when decoding quantized tensors.
- Target floating-point precision when
process_device(cuda|cpu, defaultcuda):- Execution device for per-tensor FP32 CWB math; automatically falls back to
cpuper tensor on CUDA OOM.
- Execution device for per-tensor FP32 CWB math; automatically falls back to
exclude_patterns(String, multiline, default""):- Regex (or glob when
glob_patterns=True) patterns. Preserves matching tensors frommodel_awheninclude_mode=False, or whitelists matching tensors for grafting wheninclude_mode=True.
- Regex (or glob when
discard_patterns(String, multiline, default""):- Regex (or glob) patterns of tensors to omit completely from the saved model.
glob_patterns(Boolean, defaultFalse):- Interpret
exclude_patternsanddiscard_patternsas shell-style globs (*,?) instead of regular expressions.
- Interpret
lazy_load(Boolean, defaultTrue):- Enable low-memory UEL streaming so only the current work unit resides in memory.
force_clear_cache(Boolean, defaultFalse):- Run
gc.collect()andtorch.cuda.empty_cache()before each tensor work unit.
- Run
override_dtype(Boolean, defaultFalse):- Force grafted floating tensors to
save_dtype; whenFalse, each grafted tensor preservesmodel_a's floating dtype.
- Force grafted floating tensors to
include_mode(Boolean, defaultFalse):- Invert
exclude_patternsinto a whitelist so only matching tensors are eligible for grafting.
- Invert
Outputs
output_filename(*/io.AnyType): Category-relative filename (<output_filename>.safetensors) ready to connect directly to diffusion model loader nodes.documentation(STRING): Complete markdown documentation forCWB Model Graft.cwb_report(STRING): Diagnostic report detailing active attention/FFN presets, candidate/accepted alignment matches, consensus similarity statistics, CPU fallbacks, total grafted tensor count, and total preserved base tensor count.