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 커뮤니티가 만든 AI 스킬을 발견하고 탐색하세요.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
직접 명령은 검토 Prompt를 거치지 않습니다. 실행하기 전에 소스를 확인하세요.
npx skills add https://github.com/ADu2021/skillXiv --skill endocot-internal-chain-of-thought명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? SkillsMP에서 현재 제공할 수 있는 파일을 다운로드하세요.
Zip 다운로드 다운로드 중... 이 저장소의 다른 Skills meaningful-kebab-case-name Convert arXiv papers into ready-to-use agent skills using category-aware extraction. First classifies the paper into one or more of 11 research categories, then applies a specialized extraction pipeline for each category — because different types of papers produce different types of usable knowledge. A single paper can yield multiple skills if it spans categories. Use this skill whenever the user wants to turn a paper into a skill, extract practical techniques from research, build a skill library from papers, convert arXiv papers into reusable agent instructions, or batch-process multiple papers into skills. Also trigger when someone asks about extracting actionable knowledge from papers, making research practical for LLM agents, or systematically converting academic contributions into structured agent capabilities.
action-quantization-behavior-cloning Establish regret bounds for behavior cloning with discretized actions combining statistical error and quantization error terms. Prove smoothness requirements for safe quantizer design, show that learning-based quantizers fail these requirements, and propose model-based augmentation to reduce error dependence from H² to H.
adaptive-lora-personalized-ranks Dynamically allocate LoRA ranks per-layer during fine-tuning instead of using fixed uniform ranks. Learn optimal rank for each layer and subject via variational framework with discretized exponential distribution, reducing memory footprint while maintaining fidelity and text-alignment.
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