Skip to main content 首页 创作者 adu2021 skillxiv endocot-internal-chain-of-thought
endocot-internal-chain-of-thought Enable step-by-step reasoning in diffusion models through iterative latent state refinement. Condition diffusion on evolving thought states across multiple reasoning steps, grounded with textual supervision to prevent drift.
跳到安装 Skills Marketplace 发现并探索由社区构建的 Agent Skills
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/ADu2021/skillXiv --skill endocot-internal-chain-of-thought命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
下载 Zip 下载中... name endocot-internal-chain-of-thought title EndoCoT: Scaling Endogenous Chain-of-Thought Reasoning in Diffusion Models version 0.0.2 engine skillxiv-v0.0.2-claude-opus-4.6 license MIT url https://arxiv.org/abs/2603.12252 keywords ["Diffusion","Reasoning","Chain-of-Thought","Latent Space","Generation"] description Enable step-by-step reasoning in diffusion models through iterative latent state refinement. Condition diffusion on evolving thought states across multiple reasoning steps, grounded with textual supervision to prevent drift.
Technique: Endogenous Chain-of-Thought via Iterative Latent Refinement
Diffusion models generate images by denoising—but they commit to solutions early in this process. EndoCoT enables intermediate reasoning by allowing the conditioning signal to evolve across steps. Rather than static guidance, the framework iteratively refines hidden states representing thoughts, each conditioned on the previous step's reasoning, then uses these refined states to guide generation.
This "endogenous" approach contrasts with external chain-of-thought: reasoning happens within the diffusion process via latent dynamics, enabling truly integrated visual-linguistic reasoning.
Core Concept
EndoCoT combines three mechanisms:
Iterative Thought Guidance : Refine hidden states across multiple reasoning steps before denoising
Terminal Thought Grounding : Align final reasoning state with explicit textual reference using semantic loss
Progressive Training : First supervise intermediate steps, then optimize final output quality
This enables dynamic, evolving conditioning that guides diffusion through a reasoning trajectory.
Architecture Overview
MLLM backbone : Language model for thought generation
Hidden state buffer : Evolving reasoning representations across steps
Thought refinement network : Updates states based on prior reasoning
Text reference encoder : Grounds final thoughts in language
DiT decoder : Diffusion transformer conditioned on thought states
Progressive loss scheduler : Balance reasoning supervision vs output quality
Implementation Steps
Step 1: Iterative Hidden State Refinement
Refine latent reasoning states across multiple steps before using for generation.
import torch
import torch.nn as nn
class IterativeThoughtRefiner (nn.Module):
def __init__ (self, hidden_dim=768 , num_reasoning_steps=4 ):
super ().__init__()
self .hidden_dim = hidden_dim
.num_reasoning_steps = num_reasoning_steps
.refiner_layers = nn.ModuleList([
nn.Sequential(
nn.Linear(hidden_dim, hidden_dim * ),
nn.ReLU(),
nn.Linear(hidden_dim * , hidden_dim)
)
_ (num_reasoning_steps)
])
.attention_layers = nn.ModuleList([
nn.MultiheadAttention(hidden_dim, num_heads= , batch_first= )
_ (num_reasoning_steps)
])
( ):
thought_trajectory = [initial_thought]
current_thought = initial_thought
step ( .num_reasoning_steps):
refined = .refiner_layers[step](current_thought)
attended, _ = .attention_layers[step](
refined.unsqueeze( ),
reasoning_context,
reasoning_context
)
current_thought = refined + attended.squeeze( )
thought_trajectory.append(current_thought)
torch.stack(thought_trajectory, dim= )
self
self
2
2
for
in
range
self
8
True
for
in
range
def
forward
self, initial_thought, reasoning_context
"""
Iteratively refine thought representations.
initial_thought: (batch, hidden_dim) initial hidden state
reasoning_context: (batch, seq_len, hidden_dim) context from MLLM
"""
for
in
range
self
self
self
1
1
return
1
Step 2: Terminal Thought Grounding with Text Supervision Anchor final reasoning state to explicit textual reference to prevent drift.
class TerminalThoughtGrounder (nn.Module):
def __init__ (self, hidden_dim=768 , text_encoder=None ):
super ().__init__()
self .hidden_dim = hidden_dim
self .text_encoder = text_encoder
self .thought_projector = nn.Linear(hidden_dim, hidden_dim)
self .text_projector = nn.Linear(hidden_dim, hidden_dim)
def ground_with_text (self, final_thought, reference_text ):
"""
Align final thought with textual reference using semantic loss.
final_thought: (batch, hidden_dim)
reference_text: str or tokenized reference
"""
if isinstance (reference_text, str ):
reference_embedding = self .text_encoder.encode(reference_text)
else :
reference_embedding = self .text_encoder(reference_text)
thought_proj = self .thought_projector(final_thought)
text_proj = self .text_projector(reference_embedding)
alignment_loss = torch.nn.functional.mse_loss(thought_proj, text_proj)
return alignment_loss
def forward (self, thought_trajectory, reference_text ):
"""
Compute grounding loss for final thought.
thought_trajectory: (batch, steps, hidden_dim)
reference_text: reference for grounding
"""
final_thought = thought_trajectory[:, -1 , :]
grounding_loss = self .ground_with_text(final_thought, reference_text)
return grounding_loss
Step 3: Conditional Diffusion with Evolving Thought Use thought trajectory to condition diffusion generation at each step.
class DiffusionTransformerWithEvolvedThoughts (nn.Module):
def __init__ (self, dit_model, hidden_dim=768 ):
super ().__init__()
self .dit = dit_model
self .hidden_dim = hidden_dim
self .thought_to_condition = nn.Linear(hidden_dim, dit_model.cond_dim)
def forward (
self,
noise,
timestep,
thought_trajectory,
instruction_tokens=None
):
"""
Run one diffusion step with evolved thought conditioning.
noise: (batch, channels, height, width)
timestep: int or (batch,)
thought_trajectory: (batch, steps, hidden_dim)
instruction_tokens: optional additional conditioning
"""
batch_size = noise.shape[0 ]
progress = timestep / 1000
step_idx = min (
int (progress * thought_trajectory.shape[1 ]),
thought_trajectory.shape[1 ] - 1
)
current_thought = thought_trajectory[:, step_idx, :]
conditioning = self .thought_to_condition(current_thought)
if instruction_tokens is not None :
conditioning = torch.cat([conditioning, instruction_tokens], dim=-1 )
model_output = self .dit(
noise,
timestep,
c=conditioning
)
return model_output
Step 4: Progressive Two-Stage Training First stage: supervise all intermediate reasoning steps. Second stage: optimize only final output.
def train_endocot (
model,
data_loader,
text_encoder,
num_epochs=10 ,
stage1_epochs=5
):
"""
Two-stage training: reasoning -> output quality.
"""
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4 )
for epoch in range (num_epochs):
is_stage1 = epoch < stage1_epochs
for batch_idx, (images, prompts, texts) in enumerate (data_loader):
image_noise = torch.randn_like(images)
prompt_embedding = text_encoder.encode(prompts)
thought_refiner = model.thought_refiner
thought_trajectory = thought_refiner(
prompt_embedding,
text_encoder.encode(texts).unsqueeze(1 )
)
if is_stage1:
total_loss = 0
for step_idx in range (thought_trajectory.shape[1 ]):
thought = thought_trajectory[:, step_idx, :]
outputs = model.dit_with_thoughts(
image_noise,
torch.tensor([500 ]),
thought.unsqueeze(1 )
)
step_loss = torch.nn.functional.mse_loss(outputs, images)
total_loss += step_loss
grounding_loss = model.grounder.ground_with_text(
thought_trajectory[:, -1 , :],
texts
)
total_loss += 0.1 * grounding_loss
else :
thought_trajectory = thought_trajectory.detach()
final_thought = thought_trajectory[:, -1 , :]
outputs = model.dit_with_thoughts(
image_noise,
torch.tensor([0 ]),
final_thought.unsqueeze(1 )
)
total_loss = torch.nn.functional.mse_loss(outputs, images)
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
if batch_idx % 100 == 0 :
stage = "Stage1" if is_stage1 else "Stage2"
print (f"Epoch {epoch} [{stage} ]: Loss = {total_loss.item():.4 f} " )
return model
Step 5: Integration with Prompt Engineering Demonstrate full workflow with reasoning prompts.
def generate_with_endogenous_reasoning (
model,
text_encoder,
initial_prompt,
reasoning_steps=4 ,
num_diffusion_steps=50
):
"""
Full generation pipeline with endogenous reasoning.
"""
prompt_embedding = text_encoder.encode(initial_prompt)
thought_refiner = model.thought_refiner
thought_trajectory = thought_refiner(
prompt_embedding,
torch.zeros(1 , 1 , 768 )
)
noise = torch.randn(1 , 4 , 64 , 64 )
dit_model = model.dit_with_thoughts
for diffusion_step in range (num_diffusion_steps):
timestep = (num_diffusion_steps - diffusion_step) / num_diffusion_steps
if diffusion_step % (num_diffusion_steps // reasoning_steps) == 0 :
pass
noise = dit_model(
noise,
int (timestep * 1000 ),
thought_trajectory
)
image = model.vae.decode(noise)
return image
Practical Guidance
Multi-step reasoning required for generation (e.g., "draw a car then add wheels")
Tasks benefiting from intermediate planning before generation
Scenarios where output quality depends on reasoning coherence
Fine-grained control over generation trajectory
Simple prompt-to-image tasks without reasoning requirements
Extreme latency constraints (iterative refinement adds overhead)
Tasks where early commitment to solution is beneficial
num_reasoning_steps : 2-6; more enables finer reasoning
stage1_epochs vs stage2_epochs : 50-50 split typical; adjust based on reasoning difficulty
grounding_loss weight : 0.05-0.2; stronger grounding prevents drift
thought refinement MLP hidden dim : Match backbone hidden dimension
Insufficient grounding loss causing thought drift
Over-weighting intermediate supervision (stage 1), hurting final quality
Thought trajectory too rigid (insufficient refinement network capacity)
Misalignment between thought dimensionality and DIT conditioning
Reference