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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training pipeline for CAT V3."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from typing import Dict, List, Optional
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from torch.utils.data import DataLoader
|
| 11 |
+
|
| 12 |
+
from cat_v3.dataset import (
|
| 13 |
+
DOMAINS,
|
| 14 |
+
ConceptVocabulary,
|
| 15 |
+
SimpleCharTokenizer,
|
| 16 |
+
CATV3Dataset,
|
| 17 |
+
grow_dataset,
|
| 18 |
+
build_expert_graphs
|
| 19 |
+
)
|
| 20 |
+
from cat_v3.model import CATV3Model
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def cat_v3_loss(
|
| 24 |
+
outputs: Dict[str, torch.Tensor],
|
| 25 |
+
router_target: torch.Tensor,
|
| 26 |
+
path_ids: torch.Tensor,
|
| 27 |
+
response_targets: torch.Tensor,
|
| 28 |
+
pad_id: int,
|
| 29 |
+
model: nn.Module,
|
| 30 |
+
) -> Tuple[torch.Tensor, Dict[str, float]]:
|
| 31 |
+
"""Computes joint multi-task loss: Router BCE + GAT Experts CE + Causal Decoder CE."""
|
| 32 |
+
batch_size = router_target.size(0)
|
| 33 |
+
num_concepts = outputs["fused_scores"].size(1)
|
| 34 |
+
|
| 35 |
+
# 1. Router Loss (BCE)
|
| 36 |
+
router_logits = outputs["router_logits"]
|
| 37 |
+
loss_router = F.binary_cross_entropy_with_logits(router_logits, router_target)
|
| 38 |
+
|
| 39 |
+
# 2. Experts Loss (Cross-Entropy on paths for active experts)
|
| 40 |
+
loss_experts = torch.tensor(0.0, device=router_target.device)
|
| 41 |
+
active_expert_count = 0
|
| 42 |
+
|
| 43 |
+
for idx, domain in enumerate(DOMAINS):
|
| 44 |
+
expert_out = outputs["expert_reports"][domain]
|
| 45 |
+
expert_logits = expert_out["path_logits"] # [B, path_length, num_concepts]
|
| 46 |
+
path_len = expert_logits.size(1)
|
| 47 |
+
|
| 48 |
+
# Extract filtered target path for this expert
|
| 49 |
+
expert_target_path = expert_out.get("target_path")
|
| 50 |
+
if expert_target_path is None:
|
| 51 |
+
expert_target_path = path_ids[:, :path_len]
|
| 52 |
+
|
| 53 |
+
# Calculate CE step-by-step against the filtered domain-specific path
|
| 54 |
+
ce = F.cross_entropy(
|
| 55 |
+
expert_logits.view(-1, num_concepts),
|
| 56 |
+
expert_target_path.reshape(-1),
|
| 57 |
+
reduction="none"
|
| 58 |
+
).view(batch_size, path_len).mean(dim=1) # [B]
|
| 59 |
+
|
| 60 |
+
# Mask out samples where this expert has no concepts in the path
|
| 61 |
+
expert_module = model.experts[domain]
|
| 62 |
+
domain_nodes = set(expert_module.edge_index.view(-1).cpu().tolist())
|
| 63 |
+
domain_nodes.discard(expert_module.eos_id)
|
| 64 |
+
domain_nodes.discard(expert_module.pad_id)
|
| 65 |
+
|
| 66 |
+
has_domain_concept = torch.zeros(batch_size, dtype=torch.float, device=router_target.device)
|
| 67 |
+
for b in range(batch_size):
|
| 68 |
+
for val in expert_target_path[b].tolist():
|
| 69 |
+
if val in domain_nodes:
|
| 70 |
+
has_domain_concept[b] = 1.0
|
| 71 |
+
break
|
| 72 |
+
|
| 73 |
+
# Active weight is router activation * has_domain_concept
|
| 74 |
+
active_weight = router_target[:, idx] * has_domain_concept
|
| 75 |
+
if active_weight.sum() > 0:
|
| 76 |
+
loss_experts = loss_experts + (ce * active_weight).sum() / active_weight.sum()
|
| 77 |
+
active_expert_count += 1
|
| 78 |
+
|
| 79 |
+
if active_expert_count > 0:
|
| 80 |
+
loss_experts = loss_experts / active_expert_count
|
| 81 |
+
|
| 82 |
+
# 3. Decoder Loss (Cross-Entropy on target words)
|
| 83 |
+
decoder_logits = outputs["decoder_logits"] # [B, seq_len-1, vocab_size]
|
| 84 |
+
loss_decoder = F.cross_entropy(
|
| 85 |
+
decoder_logits.reshape(-1, decoder_logits.size(-1)),
|
| 86 |
+
response_targets.reshape(-1),
|
| 87 |
+
ignore_index=pad_id
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# Total loss
|
| 91 |
+
total_loss = 0.5 * loss_router + 1.0 * loss_experts + 1.0 * loss_decoder
|
| 92 |
+
|
| 93 |
+
return total_loss, {
|
| 94 |
+
"loss_total": total_loss.item(),
|
| 95 |
+
"loss_router": loss_router.item(),
|
| 96 |
+
"loss_experts": loss_experts.item(),
|
| 97 |
+
"loss_decoder": loss_decoder.item()
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def train_cat_v3(
|
| 102 |
+
epochs: int = 20,
|
| 103 |
+
batch_size: int = 8,
|
| 104 |
+
lr: float = 5e-4,
|
| 105 |
+
checkpoint_dir: str = "checkpoints/cat_v3",
|
| 106 |
+
) -> CATV3Model:
|
| 107 |
+
"""Trains the full CAT V3 prototype model."""
|
| 108 |
+
os.makedirs(checkpoint_dir, exist_ok=True)
|
| 109 |
+
|
| 110 |
+
# 1. Prepare data
|
| 111 |
+
raw_data = grow_dataset()
|
| 112 |
+
|
| 113 |
+
# Get all texts to fit the decoder tokenizer vocab
|
| 114 |
+
all_texts = [d["question"] for d in raw_data] + [d["response"] for d in raw_data]
|
| 115 |
+
tokenizer = SimpleCharTokenizer(all_texts)
|
| 116 |
+
|
| 117 |
+
vocab = ConceptVocabulary({d: list(set(grow_dataset()[0]["concept_paths"][0])) for d in DOMAINS})
|
| 118 |
+
# Re-extract all concepts from dataset to build clean vocabulary
|
| 119 |
+
concept_lists = {}
|
| 120 |
+
for d in DOMAINS:
|
| 121 |
+
concept_lists[d] = []
|
| 122 |
+
|
| 123 |
+
for item in raw_data:
|
| 124 |
+
# Sort concepts by domain
|
| 125 |
+
for domain in item["active_experts"]:
|
| 126 |
+
for path in item["concept_paths"]:
|
| 127 |
+
for concept in path:
|
| 128 |
+
concept_lists[domain].append(concept)
|
| 129 |
+
|
| 130 |
+
# Ensure every domain has some concepts
|
| 131 |
+
for d in DOMAINS:
|
| 132 |
+
concept_lists[d] = list(set(concept_lists[d]))
|
| 133 |
+
if not concept_lists[d]:
|
| 134 |
+
# fallback
|
| 135 |
+
concept_lists[d] = ["entropy", "load"]
|
| 136 |
+
|
| 137 |
+
vocab = ConceptVocabulary(concept_lists)
|
| 138 |
+
expert_graphs = build_expert_graphs(vocab, raw_data)
|
| 139 |
+
|
| 140 |
+
dataset = CATV3Dataset(raw_data, concept_vocab=vocab, token_tokenizer=tokenizer)
|
| 141 |
+
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
|
| 142 |
+
|
| 143 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 144 |
+
print(f"Training CAT V3 on device: {device}")
|
| 145 |
+
|
| 146 |
+
# 2. Initialize Model
|
| 147 |
+
model = CATV3Model(
|
| 148 |
+
num_concepts=vocab.size(),
|
| 149 |
+
tokenizer_vocab_size=tokenizer.vocab_size(),
|
| 150 |
+
pad_id=tokenizer.pad_id,
|
| 151 |
+
eos_id=tokenizer.eos_id,
|
| 152 |
+
expert_graphs=expert_graphs,
|
| 153 |
+
concept_dim=128,
|
| 154 |
+
hidden_size=128,
|
| 155 |
+
path_length=8,
|
| 156 |
+
top_m=8,
|
| 157 |
+
decoder_vocab_size=tokenizer.vocab_size()
|
| 158 |
+
).to(device)
|
| 159 |
+
|
| 160 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4)
|
| 161 |
+
|
| 162 |
+
# 3. Training loop
|
| 163 |
+
model.train()
|
| 164 |
+
for epoch in range(epochs):
|
| 165 |
+
epoch_losses = {"loss_total": 0.0, "loss_router": 0.0, "loss_experts": 0.0, "loss_decoder": 0.0}
|
| 166 |
+
steps = 0
|
| 167 |
+
|
| 168 |
+
for batch in dataloader:
|
| 169 |
+
input_ids = batch["input_ids"].to(device)
|
| 170 |
+
attention_mask = batch["attention_mask"].to(device)
|
| 171 |
+
router_target = batch["router_target"].to(device)
|
| 172 |
+
path_ids = batch["path_ids"].to(device)
|
| 173 |
+
response_ids = batch["response_ids"].to(device)
|
| 174 |
+
response_mask = batch["response_mask"].to(device)
|
| 175 |
+
|
| 176 |
+
# Shift targets for causal language modeling
|
| 177 |
+
decoder_inputs = response_ids[:, :-1]
|
| 178 |
+
decoder_targets = response_ids[:, 1:]
|
| 179 |
+
decoder_attention_mask = response_mask[:, :-1]
|
| 180 |
+
|
| 181 |
+
optimizer.zero_grad()
|
| 182 |
+
|
| 183 |
+
outputs = model(
|
| 184 |
+
input_ids=input_ids,
|
| 185 |
+
attention_mask=attention_mask,
|
| 186 |
+
target_paths=path_ids,
|
| 187 |
+
target_responses=decoder_inputs,
|
| 188 |
+
target_responses_mask=decoder_attention_mask,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
loss, metrics = cat_v3_loss(
|
| 192 |
+
outputs=outputs,
|
| 193 |
+
router_target=router_target,
|
| 194 |
+
path_ids=path_ids,
|
| 195 |
+
response_targets=decoder_targets,
|
| 196 |
+
pad_id=tokenizer.pad_id,
|
| 197 |
+
model=model
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
loss.backward()
|
| 201 |
+
optimizer.step()
|
| 202 |
+
|
| 203 |
+
for k, v in metrics.items():
|
| 204 |
+
epoch_losses[k] += v
|
| 205 |
+
steps += 1
|
| 206 |
+
|
| 207 |
+
# Log epoch summary
|
| 208 |
+
if (epoch + 1) % 5 == 0 or epoch == 0:
|
| 209 |
+
avg_loss = {k: v / steps for k, v in epoch_losses.items()}
|
| 210 |
+
print(
|
| 211 |
+
f"Epoch {epoch+1:02d}/{epochs:02d} - "
|
| 212 |
+
f"Total: {avg_loss['loss_total']:.4f} | "
|
| 213 |
+
f"Router: {avg_loss['loss_router']:.4f} | "
|
| 214 |
+
f"Experts: {avg_loss['loss_experts']:.4f} | "
|
| 215 |
+
f"Decoder: {avg_loss['loss_decoder']:.4f}"
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
# Save checkpoint
|
| 219 |
+
checkpoint_path = os.path.join(checkpoint_dir, "cat_v3_model.pt")
|
| 220 |
+
torch.save({
|
| 221 |
+
"model_state_dict": model.state_dict(),
|
| 222 |
+
"vocab": vocab,
|
| 223 |
+
"tokenizer": tokenizer,
|
| 224 |
+
"expert_graphs": expert_graphs,
|
| 225 |
+
}, checkpoint_path)
|
| 226 |
+
print(f"Model saved to {checkpoint_path}")
|
| 227 |
+
|
| 228 |
+
return model
|