Compare commits

..

No commits in common. "2f6995d667163b5a1010a5a2d2df3e45419ae6d8" and "afd4fd1f0f2ded1331eee268e2c257357f311453" have entirely different histories.

6 changed files with 111 additions and 1503 deletions

View File

@ -50,12 +50,6 @@ class LMConfig(PretrainedConfig):
use_token_memory: bool = True, # 🔥 1.4.6: 新增token-based memory flag use_token_memory: bool = True, # 🔥 1.4.6: 新增token-based memory flag
freeze_ratio: float = 0.2, # 🔥 新增: memory_bank冻结率 (0.0表示不冻结0.2表示20%条目不更新) freeze_ratio: float = 0.2, # 🔥 新增: memory_bank冻结率 (0.0表示不冻结0.2表示20%条目不更新)
#################################################### ####################################################
# Experiment 1.4.9: Gumbel-Softmax + Diversity Loss
####################################################
num_candidates: int = 32, # 🔥 实验1.4.9: 候选记忆条目数量
num_selected: int = 1, # 🔥 实验1.4.9: 选中的记忆条目数量 (现在只选1个最佳)
gumbel_temperature: float = 1.0, # 🔥 实验1.4.9: Gumbel-Softmax温度参数
####################################################
# Triple extraction related configurations # Triple extraction related configurations
#################################################### ####################################################
max_subject_len: int = 8, max_subject_len: int = 8,
@ -105,12 +99,6 @@ class LMConfig(PretrainedConfig):
self.use_token_memory = use_token_memory # 🔥 1.4.6: token-based memory flag self.use_token_memory = use_token_memory # 🔥 1.4.6: token-based memory flag
self.freeze_ratio = freeze_ratio # 🔥 新增: memory_bank冻结率 self.freeze_ratio = freeze_ratio # 🔥 新增: memory_bank冻结率
#################################################### ####################################################
# Experiment 1.4.9: Gumbel-Softmax + Diversity Loss
####################################################
self.num_candidates = num_candidates
self.num_selected = num_selected
self.gumbel_temperature = gumbel_temperature
####################################################
# Triple extraction related configurations # Triple extraction related configurations
#################################################### ####################################################
self.max_subject_len = max_subject_len self.max_subject_len = max_subject_len

View File

@ -123,15 +123,14 @@ class Attention(nn.Module):
class MemoryGate(nn.Module): class MemoryGate(nn.Module):
"""Product Key Memory-based gate mechanism for memory selection with Gumbel-Softmax""" """Product Key Memory-based gate mechanism for memory selection"""
def __init__(self, config: LMConfig): def __init__(self, config: LMConfig):
super().__init__() super().__init__()
self.config = config self.config = config
self.dim = config.dim self.dim = config.dim
self.knowledge_num = config.knowledge_num self.knowledge_num = config.knowledge_num
self.knowledge_dim = config.knowledge_dim self.knowledge_dim = config.knowledge_dim
self.num_candidates = getattr(config, 'num_candidates', 32) # Generate 32 candidates self.num_selected = getattr(config, 'num_selected', 16)
self.num_selected = getattr(config, 'num_selected', 1) # Select 1 best from candidates
# 确保知识库数量是完全平方数 # 确保知识库数量是完全平方数
assert int(self.knowledge_num ** 0.5) ** 2 == self.knowledge_num, \ assert int(self.knowledge_num ** 0.5) ** 2 == self.knowledge_num, \
@ -170,28 +169,29 @@ class MemoryGate(nn.Module):
scores_1 = torch.einsum('bsd,kd->bsk', q1, self.keys[0]) # [batch, seq_len, num_keys] scores_1 = torch.einsum('bsd,kd->bsk', q1, self.keys[0]) # [batch, seq_len, num_keys]
scores_2 = torch.einsum('bsd,kd->bsk', q2, self.keys[1]) # [batch, seq_len, num_keys] scores_2 = torch.einsum('bsd,kd->bsk', q2, self.keys[1]) # [batch, seq_len, num_keys]
# 获取top-k candidates (now using num_candidates instead of num_selected) # 获取top-k
topk_scores_1, topk_indices_1 = scores_1.topk(self.num_candidates, dim=-1) topk_scores_1, topk_indices_1 = scores_1.topk(self.num_selected, dim=-1)
topk_scores_2, topk_indices_2 = scores_2.topk(self.num_candidates, dim=-1) topk_scores_2, topk_indices_2 = scores_2.topk(self.num_selected, dim=-1)
# 组合product key的结果 # 组合product key的结果
combined_scores = topk_scores_1.unsqueeze(-1) + topk_scores_2.unsqueeze(-2) # [batch, seq_len, num_candidates, num_candidates] combined_scores = topk_scores_1.unsqueeze(-1) + topk_scores_2.unsqueeze(-2) # [batch, seq_len, num_selected, num_selected]
combined_indices = topk_indices_1.unsqueeze(-1) * self.num_keys + topk_indices_2.unsqueeze(-2) # [batch, seq_len, num_candidates, num_candidates] combined_indices = topk_indices_1.unsqueeze(-1) * self.num_keys + topk_indices_2.unsqueeze(-2) # [batch, seq_len, num_selected, num_selected]
# 展平并选择最终的top-k candidates # 展平并选择最终的top-k
combined_scores = combined_scores.view(bsz, seq_len, -1) combined_scores = combined_scores.view(bsz, seq_len, -1)
combined_indices = combined_indices.view(bsz, seq_len, -1) combined_indices = combined_indices.view(bsz, seq_len, -1)
candidate_scores, candidate_pk_indices = combined_scores.topk(self.num_candidates, dim=-1) final_scores, final_pk_indices = combined_scores.topk(self.num_selected, dim=-1)
candidate_indices = combined_indices.gather(-1, candidate_pk_indices) # [batch, seq_len, num_candidates] memory_indices = combined_indices.gather(-1, final_pk_indices)
# 归一化候选分数 # 归一化分数
candidate_scores = F.softmax(candidate_scores, dim=-1) memory_scores = F.softmax(final_scores, dim=-1)
candidate_scores = self.dropout(candidate_scores) memory_scores = self.dropout(memory_scores)
# 返回候选项用于后续的相似度选择 # 计算平衡损失和监控统计
# 注意这里返回候选项在MiniMindBlock中进行相似度选择和多样性损失计算 balance_loss, stats = self._compute_balance_loss_and_stats(memory_indices, memory_scores)
return candidate_indices, candidate_scores, None, {}
return memory_indices, memory_scores, balance_loss, stats
def _compute_balance_loss_and_stats(self, memory_indices, memory_scores): def _compute_balance_loss_and_stats(self, memory_indices, memory_scores):
""" """
@ -276,10 +276,10 @@ class GatedMemoryFusion(nn.Module):
self.config = config self.config = config
self.dim = config.dim self.dim = config.dim
self.knowledge_dim = config.knowledge_dim self.knowledge_dim = config.knowledge_dim
self.num_selected = getattr(config, 'num_selected', 1) # Now we select 1 best memory self.num_selected = getattr(config, 'num_selected', 16)
# 输入维度dim (h_attn) + num_selected * dim (选中的记忆现在只有1个) # 输入维度dim (h_attn) + num_selected * knowledge_dim (选中的记忆)
# 实验1.4.9修改为只选择1个最佳记忆 # 实验1.4.6记忆解码后立即压缩回knowledge_dim避免显存爆炸
concat_dim = self.dim + self.num_selected * self.dim concat_dim = self.dim + self.num_selected * self.dim
# 类似SwiGLU的门控MLP结构 # 类似SwiGLU的门控MLP结构
@ -289,18 +289,23 @@ class GatedMemoryFusion(nn.Module):
self.dropout = nn.Dropout(config.dropout) self.dropout = nn.Dropout(config.dropout)
def forward(self, h_attn: torch.Tensor, selected_memory: torch.Tensor): def forward(self, h_attn: torch.Tensor, selected_memories: torch.Tensor, memory_scores: torch.Tensor):
""" """
Args: Args:
h_attn: [batch_size, seq_len, dim] - Self attention output h_attn: [batch_size, seq_len, dim] - Self attention output
selected_memory: [batch_size, seq_len, dim] - Selected single best memory selected_memories: [batch_size, seq_len, num_selected, knowledge_dim] - Selected memory data
memory_scores: [batch_size, seq_len, num_selected] - Memory selection weights (not used in concatenation approach)
Returns: Returns:
output: [batch_size, seq_len, dim] output: [batch_size, seq_len, dim]
""" """
bsz, seq_len, _ = h_attn.shape bsz, seq_len, _ = h_attn.shape
# 拼接h_attn和最佳记忆 # 将选中的记忆展平为一维向量
concat_input = torch.cat([h_attn, selected_memory], dim=-1) # [batch, seq_len, dim + dim] # [batch, seq_len, num_selected, knowledge_dim] -> [batch, seq_len, num_selected * knowledge_dim]
memory_flat = selected_memories.reshape(bsz, seq_len, -1)
# 拼接h_attn和记忆信息
concat_input = torch.cat([h_attn, memory_flat], dim=-1) # [batch, seq_len, dim + num_selected * dim]
# 门控MLP处理类似SwiGLU # 门控MLP处理类似SwiGLU
gate = F.silu(self.gate_proj(concat_input)) # [batch, seq_len, dim] gate = F.silu(self.gate_proj(concat_input)) # [batch, seq_len, dim]
@ -332,96 +337,22 @@ class MiniMindBlock(nn.Module):
self.memory_gate = MemoryGate(config) self.memory_gate = MemoryGate(config)
self.gated_memory_fusion = GatedMemoryFusion(config) self.gated_memory_fusion = GatedMemoryFusion(config)
# Gumbel-Softmax参数
self.gumbel_temperature = getattr(config, 'gumbel_temperature', 1.0)
# self.attentionpool = nn.Linear(config.dim, 1) # self.attentionpool = nn.Linear(config.dim, 1)
def gumbel_softmax_selection(self, similarity_scores, temperature=1.0, hard=True):
"""
使用Gumbel-Softmax进行可微分的离散选择
Args:
similarity_scores: [batch_size, seq_len, num_candidates] - 相似度分数
temperature: Gumbel-Softmax温度参数
hard: 是否使用硬选择one-hot
Returns:
selection_weights: [batch_size, seq_len, num_candidates] - 选择权重
selected_indices: [batch_size, seq_len] - 选中的索引用于统计
"""
# 添加Gumbel噪声
gumbel_noise = -torch.log(-torch.log(torch.rand_like(similarity_scores) + 1e-20) + 1e-20)
logits = (similarity_scores + gumbel_noise) / temperature
# Softmax
soft_weights = F.softmax(logits, dim=-1)
if hard:
# 硬选择创建one-hot向量
_, max_indices = soft_weights.max(dim=-1, keepdim=True)
hard_weights = torch.zeros_like(soft_weights).scatter_(-1, max_indices, 1.0)
# 使用straight-through estimator
selection_weights = hard_weights - soft_weights.detach() + soft_weights
selected_indices = max_indices.squeeze(-1) # [batch_size, seq_len]
else:
# 软选择
selection_weights = soft_weights
selected_indices = torch.argmax(soft_weights, dim=-1)
return selection_weights, selected_indices
def compute_diversity_loss(self, candidate_memories):
"""
计算候选集内部多样性损失鼓励候选项之间的差异性
Args:
candidate_memories: [batch_size, seq_len, num_candidates, dim]
Returns:
diversity_loss: 标量张量
"""
bsz, seq_len, num_candidates, dim = candidate_memories.shape
# 计算候选项之间的相似度矩阵
# 归一化候选记忆用于计算余弦相似度
normalized_memories = F.normalize(candidate_memories, p=2, dim=-1) # [batch, seq_len, num_candidates, dim]
# 计算相似度矩阵: [batch, seq_len, num_candidates, num_candidates]
similarity_matrix = torch.matmul(normalized_memories, normalized_memories.transpose(-2, -1))
# 移除对角线(自相似度=1
mask = torch.eye(num_candidates, device=candidate_memories.device).bool()
mask = mask.unsqueeze(0).unsqueeze(0).expand(bsz, seq_len, -1, -1)
# 计算非对角线元素的平均相似度(希望越小越好,表示越多样)
off_diagonal_similarities = similarity_matrix.masked_select(~mask)
avg_similarity = off_diagonal_similarities.mean()
# 多样性损失:相似度越高,损失越大
diversity_loss = avg_similarity
return diversity_loss
def forward(self, x, pos_cis, memory_bank, tok_embeddings, collect_ema_stats=False): def forward(self, x, pos_cis, memory_bank, tok_embeddings, collect_ema_stats=False):
""" """
实验1.4.9: Gumbel-Softmax + 多样性损失 + 可微分相似度损失
Args: Args:
x: [batch_size, seq_len, dim] x: [batch_size, seq_len, dim]
pos_cis: positional encoding pos_cis: positional encoding
memory_bank: [knowledge_num, knowledge_length] - shared memory bank with token IDs memory_bank: [knowledge_num, knowledge_dim] - shared memory bank
tok_embeddings: token embedding layer
collect_ema_stats: 是否收集EMA更新统计信息 collect_ema_stats: 是否收集EMA更新统计信息
Returns: Returns:
out: [batch_size, seq_len, dim] out: [batch_size, seq_len, dim]
balance_loss: 该层的平衡损失 (从候选项计算) balance_loss: 该层的平衡损失
similarity_loss: 相似度损失 (可微分)
diversity_loss: 多样性损失
layer_stats: 该层的监控统计信息 layer_stats: 该层的监控统计信息
ema_stats: EMA更新统计信息如果collect_ema_stats=True ema_stats: EMA更新统计信息如果collect_ema_stats=True
cosine_stats: 查找向量与选记忆条目的余弦相似度统计信息 cosine_stats: 查找向量与选中记忆条目的余弦相似度统计信息
""" """
# Self attention # Self attention
h_attn = self.attention(self.attention_norm(x), pos_cis) h_attn = self.attention(self.attention_norm(x), pos_cis)
@ -430,147 +361,68 @@ class MiniMindBlock(nn.Module):
# 使用h_attn作为门控和交叉注意力的输入核心self attention的输出 # 使用h_attn作为门控和交叉注意力的输入核心self attention的输出
h_for_memory = self.memory_norm(h_attn) h_for_memory = self.memory_norm(h_attn)
# 🔥 新架构生成32个候选项 # 门控选择记忆
candidate_indices, candidate_scores, _, _ = self.memory_gate(h_for_memory) memory_indices, memory_scores, balance_loss, layer_stats = self.memory_gate(h_for_memory)
# candidate_indices: [batch, seq_len, num_candidates]
# candidate_scores: [batch, seq_len, num_candidates]
bsz, seq_len, num_candidates = candidate_indices.shape # 根据索引获取记忆数据 - 实验1.4.6解码token_id为特征向量
bsz, seq_len, num_selected = memory_indices.shape
memory_indices_flat = memory_indices.view(-1)
selected_token_ids = memory_bank[memory_indices_flat] # [batch * seq_len * num_selected, knowledge_length]
# 解码候选token_ids为特征向量 # 解码token_ids为特征向量并立即压缩避免显存爆炸
candidate_indices_flat = candidate_indices.view(-1) # [batch * seq_len * num_candidates] selected_embeddings = tok_embeddings(selected_token_ids) # [batch * seq_len * num_selected, knowledge_length, dim]
candidate_token_ids = memory_bank[candidate_indices_flat] # [batch * seq_len * num_candidates, knowledge_length]
# 解码为embeddings并池化 # 立即压缩knowledge_length * dim -> knowledge_dim 避免显存爆炸
candidate_embeddings = tok_embeddings(candidate_token_ids) # [batch * seq_len * num_candidates, knowledge_length, dim] # 使用平均池化压缩knowledge_length维度
candidate_memories = candidate_embeddings.mean(dim=1) # [batch * seq_len * num_candidates, dim] pooled_memory = selected_embeddings.mean(dim=1) # [batch * seq_len * num_selected, dim]
candidate_memories = candidate_memories.view(bsz, seq_len, num_candidates, self.dim) # [batch, seq_len, num_candidates, dim] # attn_weights = self.attentionpool(selected_embeddings)
# attn_weights = torch.softmax(attn_weights, dim=1)
# pooled_memory = torch.sum(selected_embeddings * attn_weights, dim=1)
# 🔥 核心改进: 计算可微分的相似度分数 (移除no_grad) selected_memory = pooled_memory.view(bsz, seq_len, num_selected, self.dim) # [batch, seq_len, num_selected, dim]
h_expanded = h_for_memory.unsqueeze(2).expand(-1, -1, num_candidates, -1) # [batch, seq_len, num_candidates, dim]
similarity_scores = F.cosine_similarity(h_expanded, candidate_memories, dim=-1) # [batch, seq_len, num_candidates]
# 🔥 使用Gumbel-Softmax选择最佳候选项 # 门控MLP融合串型连接h_attn和选中的记忆
selection_weights, selected_indices = self.gumbel_softmax_selection( memory_output = self.gated_memory_fusion(h_for_memory, selected_memory, memory_scores)
similarity_scores,
temperature=self.gumbel_temperature,
hard=True
) # selection_weights: [batch, seq_len, num_candidates], selected_indices: [batch, seq_len]
# 🔥 计算相似度损失 (现在是可微分的!)
# 相似度损失:希望选中的记忆与查询向量相似度尽可能高
selected_similarities = (similarity_scores * selection_weights).sum(dim=-1) # [batch, seq_len]
similarity_loss = -selected_similarities.mean() # 负号:相似度越高,损失越小
# 🔥 计算候选集多样性损失
diversity_loss = self.compute_diversity_loss(candidate_memories)
# 🔥 使用selection_weights进行加权选择最终记忆
selected_memory = (candidate_memories * selection_weights.unsqueeze(-1)).sum(dim=2) # [batch, seq_len, dim]
# 门控MLP融合只融合选中的单个最佳记忆
memory_output = self.gated_memory_fusion(h_for_memory, selected_memory)
# 残差连接 # 残差连接
out = h + memory_output out = h + memory_output
# 🔥 计算平衡损失和统计信息 (基于候选项的选择分布) # 🔍 新增: 计算查找向量与选中记忆条目的余弦相似度
balance_loss, layer_stats = self._compute_candidate_balance_stats(candidate_indices, selection_weights) with torch.no_grad():
# 🔥 计算详细的相似度统计信息 # 扩展查找向量维度以匹配selected_memory
cosine_stats = { h_expanded = h_for_memory.unsqueeze(2).expand(-1, -1, num_selected, -1) # [batch, seq_len, num_selected, dim]
'similarity_scores': similarity_scores, # [batch, seq_len, num_candidates]
'selected_similarities': selected_similarities, # [batch, seq_len]
'avg_similarity': similarity_scores.mean().item(), # 平均相似度
'max_similarity': similarity_scores.max().item(), # 最大相似度
'min_similarity': similarity_scores.min().item(), # 最小相似度
'selected_avg_similarity': selected_similarities.mean().item(), # 选中记忆的平均相似度
'selection_entropy': -torch.sum(selection_weights * torch.log(selection_weights + 1e-10), dim=-1).mean().item() # 选择熵
}
# 收集EMA更新统计信息现在基于选中的记忆 # 计算余弦相似度cosine_sim(query, memory) for each selected memory
cosine_similarities = F.cosine_similarity(
h_expanded, # [batch, seq_len, num_selected, dim]
selected_memory, # [batch, seq_len, num_selected, knowledge_dim]
dim=-1 # 在knowledge_dim维度计算余弦相似度
) # [batch, seq_len, num_selected]
# 计算余弦相似度统计信息
cosine_stats = {
'cosine_similarities': cosine_similarities, # [batch, seq_len, num_selected]
'avg_cosine_similarity': cosine_similarities.mean().item(), # 平均余弦相似度
'max_cosine_similarity': cosine_similarities.max().item(), # 最大余弦相似度
'min_cosine_similarity': cosine_similarities.min().item(), # 最小余弦相似度
'std_cosine_similarity': cosine_similarities.std().item(), # 余弦相似度标准差
}
# 收集EMA更新统计信息仅在训练时且启用时
ema_stats = None ema_stats = None
if collect_ema_stats and self.training: if collect_ema_stats and self.training:
# 扩展选中的索引以匹配EMA更新的期望格式
selected_memory_indices = candidate_indices.gather(2, selected_indices.unsqueeze(-1)) # [batch, seq_len, 1]
ema_stats = { ema_stats = {
'memory_indices': selected_memory_indices, # [batch, seq_len, 1] 'memory_indices': memory_indices, # [batch, seq_len, num_selected]
'memory_scores': torch.ones_like(selected_memory_indices.float()), # [batch, seq_len, 1] - 选中的权重为1 'memory_scores': memory_scores, # [batch, seq_len, num_selected]
'h_for_memory': h_for_memory, # [batch, seq_len, dim] 'h_for_memory': h_for_memory, # [batch, seq_len, dim]
'selected_memory': selected_memory.unsqueeze(2), # [batch, seq_len, 1, dim] 'selected_memory': selected_memory, # [batch, seq_len, num_selected, knowledge_dim]
} }
if collect_ema_stats: if collect_ema_stats:
return out, balance_loss, similarity_loss, diversity_loss, layer_stats, ema_stats, cosine_stats return out, balance_loss, layer_stats, ema_stats, cosine_stats
else: else:
return out, balance_loss, similarity_loss, diversity_loss, layer_stats, cosine_stats return out, balance_loss, layer_stats, cosine_stats
def _compute_candidate_balance_stats(self, candidate_indices, selection_weights):
"""
计算基于候选项选择的平衡损失和统计信息
Args:
candidate_indices: [batch_size, seq_len, num_candidates]
selection_weights: [batch_size, seq_len, num_candidates] - Gumbel-Softmax权重
Returns:
balance_loss: 标量张量
stats: 统计信息字典
"""
bsz, seq_len, num_candidates = candidate_indices.shape
device = candidate_indices.device
# 使用加权统计每个记忆条目被选中的概率
flat_indices = candidate_indices.view(-1) # [batch * seq_len * num_candidates]
flat_weights = selection_weights.view(-1) # [batch * seq_len * num_candidates]
# 统计每个记忆条目被选中的加权次数
memory_counts = torch.zeros(self.config.knowledge_num, device=device)
memory_counts.scatter_add_(0, flat_indices, flat_weights)
# 计算选择概率分布
total_selections = memory_counts.sum()
memory_probs = memory_counts / (total_selections + 1e-10)
# 计算KL散度损失与均匀分布的KL散度
uniform_prob = 1.0 / self.config.knowledge_num
memory_probs_safe = memory_probs + 1e-10
kl_loss = F.kl_div(
torch.log(memory_probs_safe),
torch.full_like(memory_probs, uniform_prob),
reduction='sum'
)
# 计算基尼系数损失
sorted_probs, _ = torch.sort(memory_probs)
n = self.config.knowledge_num
index = torch.arange(1, n + 1, device=device, dtype=torch.float)
gini_coeff = (2 * torch.sum(index * sorted_probs) / (n * torch.sum(sorted_probs))) - (n + 1) / n
gini_loss = gini_coeff
# 组合平衡损失
balance_loss = 0.5 * kl_loss + 0.5 * gini_loss
# 计算统计信息
with torch.no_grad():
coverage_rate = (memory_counts > 0.01).float().mean().item() # 被选中概率>1%的记忆比例
top10_threshold = torch.quantile(memory_counts, 0.9)
hot_memories = (memory_counts >= top10_threshold).sum().item()
dead_memories = (memory_counts < 0.01).sum().item() # 几乎从未被选中的记忆
selection_variance = memory_counts.var().item()
stats = {
'gini_coefficient': gini_coeff.item(),
'kl_divergence': kl_loss.item(),
'coverage_rate': coverage_rate,
'hot_memories': hot_memories,
'dead_memories': dead_memories,
'selection_variance': selection_variance,
'max_selections': memory_counts.max().item(),
'min_selections': memory_counts.min().item(),
}
return balance_loss, stats
class MiniMindLM(PreTrainedModel): class MiniMindLM(PreTrainedModel):
@ -622,12 +474,10 @@ class MiniMindLM(PreTrainedModel):
# 固定冻结前面的条目 # 固定冻结前面的条目
freeze_mask[:freeze_num] = True freeze_mask[:freeze_num] = True
self.register_buffer('freeze_mask', freeze_mask, persistent=False) self.register_buffer('freeze_mask', freeze_mask, persistent=False)
print(f"🔥 Memory bank freezing enabled: {freeze_num}/{params.knowledge_num} entries ({params.freeze_ratio*100:.1f}%) frozen", flush=True) print(f"🔥 Memory bank freezing enabled: {freeze_num}/{params.knowledge_num} entries ({params.freeze_ratio*100:.1f}%) frozen")
import sys; sys.stdout.flush()
else: else:
self.register_buffer('freeze_mask', torch.zeros(params.knowledge_num, dtype=torch.bool), persistent=False) self.register_buffer('freeze_mask', torch.zeros(params.knowledge_num, dtype=torch.bool), persistent=False)
print(f"🔥 Memory bank freezing disabled: all entries can be updated", flush=True) print(f"🔥 Memory bank freezing disabled: all entries can be updated")
import sys; sys.stdout.flush()
self.OUT = CausalLMOutputWithPast() self.OUT = CausalLMOutputWithPast()
@ -689,26 +539,20 @@ class MiniMindLM(PreTrainedModel):
h = self.dropout(self.tok_embeddings(input_ids)) h = self.dropout(self.tok_embeddings(input_ids))
pos_cis = self.pos_cis[start_pos:start_pos + input_ids.size(1)] pos_cis = self.pos_cis[start_pos:start_pos + input_ids.size(1)]
# 收集所有层的损失和统计信息 - 实验1.4.9: 四损失系统 # 收集所有层的平衡损失和统计信息
total_balance_loss = 0 total_balance_loss = 0
total_similarity_loss = 0
total_diversity_loss = 0
all_layer_stats = {} all_layer_stats = {}
all_ema_stats = {} all_ema_stats = {}
all_cosine_stats = {} all_cosine_stats = {}
for layer_idx, layer in enumerate(self.layers): for layer_idx, layer in enumerate(self.layers):
if collect_ema_stats: if collect_ema_stats:
h, balance_loss, similarity_loss, diversity_loss, layer_stats, ema_stats, cosine_stats = layer(h, pos_cis, self.memory_bank, self.tok_embeddings, collect_ema_stats=True) h, balance_loss, layer_stats, ema_stats, cosine_stats = layer(h, pos_cis, self.memory_bank, self.tok_embeddings, collect_ema_stats=True)
all_ema_stats[f'layer_{layer_idx}'] = ema_stats all_ema_stats[f'layer_{layer_idx}'] = ema_stats
else: else:
h, balance_loss, similarity_loss, diversity_loss, layer_stats, cosine_stats = layer(h, pos_cis, self.memory_bank, self.tok_embeddings, collect_ema_stats=False) h, balance_loss, layer_stats, cosine_stats = layer(h, pos_cis, self.memory_bank, self.tok_embeddings, collect_ema_stats=False)
# 累加四种损失
total_balance_loss += balance_loss total_balance_loss += balance_loss
total_similarity_loss += similarity_loss
total_diversity_loss += diversity_loss
# 为每层的统计信息添加前缀 # 为每层的统计信息添加前缀
for key, value in layer_stats.items(): for key, value in layer_stats.items():
all_layer_stats[f'layer_{layer_idx}_{key}'] = value all_layer_stats[f'layer_{layer_idx}_{key}'] = value
@ -719,12 +563,8 @@ class MiniMindLM(PreTrainedModel):
logits = self.output(self.norm(h)) logits = self.output(self.norm(h))
# 🔥 新的四损失结构 # 使用总的平衡损失作为aux_loss
aux_loss = { aux_loss = total_balance_loss
'balance_loss': total_balance_loss,
'similarity_loss': total_similarity_loss,
'diversity_loss': total_diversity_loss,
}
self.OUT.__setitem__('last_hidden_state', h) self.OUT.__setitem__('last_hidden_state', h)
self.OUT.__setitem__('logits', logits) self.OUT.__setitem__('logits', logits)

View File

@ -1,770 +0,0 @@
import math
import struct
import inspect
import time
from .LMConfig import LMConfig
from typing import Any, Optional, Tuple, List, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from transformers import PreTrainedModel
from transformers.modeling_outputs import CausalLMOutputWithPast
class RMSNorm(torch.nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
return self.weight * self._norm(x.float()).type_as(x)
def precompute_pos_cis(dim: int, end: int = int(32 * 1024), theta: float = 1e6):
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
t = torch.arange(end, device=freqs.device) # type: ignore
freqs = torch.outer(t, freqs).float() # type: ignore
pos_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
return pos_cis
def apply_rotary_emb(xq, xk, pos_cis):
def unite_shape(pos_cis, x):
ndim = x.ndim
assert 0 <= 1 < ndim
assert pos_cis.shape == (x.shape[1], x.shape[-1])
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
return pos_cis.view(*shape)
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
pos_cis = unite_shape(pos_cis, xq_)
xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3)
xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3)
return xq_out.type_as(xq), xk_out.type_as(xk)
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
"""torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
bs, slen, n_kv_heads, head_dim = x.shape
if n_rep == 1:
return x
return (
x[:, :, :, None, :]
.expand(bs, slen, n_kv_heads, n_rep, head_dim)
.reshape(bs, slen, n_kv_heads * n_rep, head_dim)
)
class Attention(nn.Module):
"""Self attention module without KV cache"""
def __init__(self, args: LMConfig):
super().__init__()
self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
assert args.n_heads % self.n_kv_heads == 0
self.n_local_heads = args.n_heads
self.n_local_kv_heads = self.n_kv_heads
self.n_rep = self.n_local_heads // self.n_local_kv_heads
self.head_dim = args.dim // args.n_heads
self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False)
self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False)
self.attn_dropout = nn.Dropout(args.dropout)
self.resid_dropout = nn.Dropout(args.dropout)
self.dropout = args.dropout
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
# print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf"))
mask = torch.triu(mask, diagonal=1)
self.register_buffer("mask", mask, persistent=False)
def forward(self, x: torch.Tensor, pos_cis: torch.Tensor):
"""Forward pass without KV cache"""
bsz, seq_len, _ = x.shape
xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
xq, xk = apply_rotary_emb(xq, xk, pos_cis)
# 注意完全去除了KV cache相关代码
xq, xk, xv = (
xq.transpose(1, 2),
repeat_kv(xk, self.n_rep).transpose(1, 2),
repeat_kv(xv, self.n_rep).transpose(1, 2)
)
if self.flash and seq_len != 1:
dropout_p = self.dropout if self.training else 0.0
output = F.scaled_dot_product_attention(
xq, xk, xv,
attn_mask=None,
dropout_p=dropout_p,
is_causal=True
)
else:
scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)
scores += self.mask[:, :, :seq_len, :seq_len]
scores = F.softmax(scores.float(), dim=-1).type_as(xq)
scores = self.attn_dropout(scores)
output = scores @ xv
output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
output = self.resid_dropout(self.wo(output))
return output
class MemoryGate(nn.Module):
"""Product Key Memory-based gate mechanism for memory selection"""
def __init__(self, config: LMConfig):
super().__init__()
self.config = config
self.dim = config.dim
self.knowledge_num = config.knowledge_num
self.knowledge_dim = config.knowledge_dim
self.num_selected = getattr(config, 'num_selected', 16)
# 确保知识库数量是完全平方数
assert int(self.knowledge_num ** 0.5) ** 2 == self.knowledge_num, \
f"knowledge_num ({self.knowledge_num}) must be a perfect square for product key memory"
self.num_keys = int(self.knowledge_num ** 0.5)
# 查询投影将输入维度映射到knowledge_dim * 2用于两个product key
self.gate_proj = nn.Linear(self.dim, self.knowledge_dim, bias=False)
# Product Key Memory: 两个独立的键集合
self.keys = nn.Parameter(torch.randn(2, self.num_keys, self.knowledge_dim // 2))
self.dropout = nn.Dropout(config.dropout)
def forward(self, x: torch.Tensor):
"""
Args:
x: [batch_size, seq_len, dim]
Returns:
memory_indices: [batch_size, seq_len, num_selected]
memory_scores: [batch_size, seq_len, num_selected]
balance_loss: 平衡损失KL散度 + 基尼系数
stats: 监控统计信息字典
"""
bsz, seq_len, _ = x.shape
# 生成查询向量
queries = self.gate_proj(x) # [batch, seq_len, knowledge_dim]
# 分割为两部分用于product key
q1 = queries[:, :, :self.knowledge_dim // 2] # [batch, seq_len, knowledge_dim // 2]
q2 = queries[:, :, self.knowledge_dim // 2:] # [batch, seq_len, knowledge_dim // 2]
# 计算与两个键集合的相似度
scores_1 = torch.einsum('bsd,kd->bsk', q1, self.keys[0]) # [batch, seq_len, num_keys]
scores_2 = torch.einsum('bsd,kd->bsk', q2, self.keys[1]) # [batch, seq_len, num_keys]
# 获取top-k
topk_scores_1, topk_indices_1 = scores_1.topk(self.num_selected, dim=-1)
topk_scores_2, topk_indices_2 = scores_2.topk(self.num_selected, dim=-1)
# 组合product key的结果
combined_scores = topk_scores_1.unsqueeze(-1) + topk_scores_2.unsqueeze(-2) # [batch, seq_len, num_selected, num_selected]
combined_indices = topk_indices_1.unsqueeze(-1) * self.num_keys + topk_indices_2.unsqueeze(-2) # [batch, seq_len, num_selected, num_selected]
# 展平并选择最终的top-k
combined_scores = combined_scores.view(bsz, seq_len, -1)
combined_indices = combined_indices.view(bsz, seq_len, -1)
final_scores, final_pk_indices = combined_scores.topk(self.num_selected, dim=-1)
memory_indices = combined_indices.gather(-1, final_pk_indices)
# 归一化分数
memory_scores = F.softmax(final_scores, dim=-1)
memory_scores = self.dropout(memory_scores)
# 计算平衡损失和监控统计
balance_loss, stats = self._compute_balance_loss_and_stats(memory_indices, memory_scores)
return memory_indices, memory_scores, balance_loss, stats
def _compute_balance_loss_and_stats(self, memory_indices, memory_scores):
"""
计算平衡损失和监控统计信息
Args:
memory_indices: [batch_size, seq_len, num_selected]
memory_scores: [batch_size, seq_len, num_selected]
Returns:
balance_loss: 标量张量
stats: 统计信息字典
"""
bsz, seq_len, num_selected = memory_indices.shape
device = memory_indices.device
# 1. 计算记忆选择分布
# 将所有选择的记忆索引展平
flat_indices = memory_indices.view(-1) # [batch_size * seq_len * num_selected]
# 统计每个记忆条目被选中的次数
memory_counts = torch.zeros(self.knowledge_num, device=device)
memory_counts.scatter_add_(0, flat_indices, torch.ones_like(flat_indices, dtype=torch.float))
# 计算选择概率分布
total_selections = bsz * seq_len * num_selected
memory_probs = memory_counts / total_selections
# 2. 计算KL散度损失与均匀分布的KL散度
uniform_prob = 1.0 / self.knowledge_num
# 避免log(0)的问题
memory_probs_safe = memory_probs + 1e-10
kl_loss = F.kl_div(
torch.log(memory_probs_safe),
torch.full_like(memory_probs, uniform_prob),
reduction='sum'
)
# 3. 计算基尼系数损失(衡量分布不平等程度)
sorted_probs, _ = torch.sort(memory_probs)
n = self.knowledge_num
index = torch.arange(1, n + 1, device=device, dtype=torch.float)
gini_coeff = (2 * torch.sum(index * sorted_probs) / (n * torch.sum(sorted_probs))) - (n + 1) / n
gini_loss = gini_coeff # 基尼系数越大,分布越不均匀
# 4. 组合平衡损失
balance_loss = 0.5 * kl_loss + 0.5 * gini_loss
# 5. 计算监控统计信息
with torch.no_grad():
# 记忆覆盖率:被选中的记忆条目占总数的比例
coverage_rate = (memory_counts > 0).float().mean().item()
# 热点记忆选择次数前10%的记忆条目
top10_threshold = torch.quantile(memory_counts, 0.9)
hot_memories = (memory_counts >= top10_threshold).sum().item()
# 死记忆:从未被选中的记忆条目
dead_memories = (memory_counts == 0).sum().item()
# 记忆选择方差(衡量不平衡程度)
selection_variance = memory_counts.var().item()
stats = {
'gini_coefficient': gini_coeff.item(),
'kl_divergence': kl_loss.item(),
'coverage_rate': coverage_rate,
'hot_memories': hot_memories,
'dead_memories': dead_memories,
'selection_variance': selection_variance,
'max_selections': memory_counts.max().item(),
'min_selections': memory_counts.min().item(),
}
return balance_loss, stats
class GatedMemoryFusion(nn.Module):
"""Gated MLP fusion for concatenated h_attn and selected memories"""
def __init__(self, config: LMConfig):
super().__init__()
self.config = config
self.dim = config.dim
self.knowledge_dim = config.knowledge_dim
self.num_selected = getattr(config, 'num_selected', 16)
# 输入维度dim (h_attn) + num_selected * knowledge_dim (选中的记忆)
# 实验1.4.6记忆解码后立即压缩回knowledge_dim避免显存爆炸
concat_dim = self.dim + self.num_selected * self.dim
# 类似SwiGLU的门控MLP结构
self.gate_proj = nn.Linear(concat_dim, self.dim, bias=False)
self.up_proj = nn.Linear(concat_dim, self.dim, bias=False)
self.down_proj = nn.Linear(self.dim, self.dim, bias=False)
self.dropout = nn.Dropout(config.dropout)
def forward(self, h_attn: torch.Tensor, selected_memories: torch.Tensor, memory_scores: torch.Tensor):
"""
Args:
h_attn: [batch_size, seq_len, dim] - Self attention output
selected_memories: [batch_size, seq_len, num_selected, knowledge_dim] - Selected memory data
memory_scores: [batch_size, seq_len, num_selected] - Memory selection weights (not used in concatenation approach)
Returns:
output: [batch_size, seq_len, dim]
"""
bsz, seq_len, _ = h_attn.shape
# 将选中的记忆展平为一维向量
# [batch, seq_len, num_selected, knowledge_dim] -> [batch, seq_len, num_selected * knowledge_dim]
memory_flat = selected_memories.reshape(bsz, seq_len, -1)
# 拼接h_attn和记忆信息
concat_input = torch.cat([h_attn, memory_flat], dim=-1) # [batch, seq_len, dim + num_selected * dim]
# 门控MLP处理类似SwiGLU
gate = F.silu(self.gate_proj(concat_input)) # [batch, seq_len, dim]
up = self.up_proj(concat_input) # [batch, seq_len, dim]
fusion_output = gate * up # Element-wise multiplication
# 输出投影
output = self.down_proj(fusion_output) # [batch, seq_len, dim]
output = self.dropout(output)
return output
class MiniMindBlock(nn.Module):
"""Transformer block with memory-based cross attention instead of FFN"""
def __init__(self, layer_id: int, config: LMConfig):
super().__init__()
self.config = config # 保存config引用
self.n_heads = config.n_heads
self.dim = config.dim
self.head_dim = config.dim // config.n_heads
self.attention = Attention(config)
self.layer_id = layer_id
self.attention_norm = RMSNorm(config.dim, eps=config.norm_eps)
self.memory_norm = RMSNorm(config.dim, eps=config.norm_eps)
# 记忆相关模块
self.memory_gate = MemoryGate(config)
self.gated_memory_fusion = GatedMemoryFusion(config)
# self.attentionpool = nn.Linear(config.dim, 1)
def forward(self, x, pos_cis, memory_bank, tok_embeddings, collect_ema_stats=False):
"""
Args:
x: [batch_size, seq_len, dim]
pos_cis: positional encoding
memory_bank: [knowledge_num, knowledge_dim] - shared memory bank
collect_ema_stats: 是否收集EMA更新统计信息
Returns:
out: [batch_size, seq_len, dim]
balance_loss: 该层的平衡损失
layer_stats: 该层的监控统计信息
ema_stats: EMA更新统计信息如果collect_ema_stats=True
cosine_stats: 查找向量与选中记忆条目的余弦相似度统计信息
"""
# Self attention
h_attn = self.attention(self.attention_norm(x), pos_cis)
h = x + h_attn
# 使用h_attn作为门控和交叉注意力的输入核心self attention的输出
h_for_memory = self.memory_norm(h_attn)
# 门控选择记忆
memory_indices, memory_scores, balance_loss, layer_stats = self.memory_gate(h_for_memory)
# 根据索引获取记忆数据 - 实验1.4.6解码token_id为特征向量
bsz, seq_len, num_selected = memory_indices.shape
memory_indices_flat = memory_indices.view(-1)
selected_token_ids = memory_bank[memory_indices_flat] # [batch * seq_len * num_selected, knowledge_length]
# 解码token_ids为特征向量并立即压缩避免显存爆炸
selected_embeddings = tok_embeddings(selected_token_ids) # [batch * seq_len * num_selected, knowledge_length, dim]
# 立即压缩knowledge_length * dim -> knowledge_dim 避免显存爆炸
# 使用平均池化压缩knowledge_length维度
pooled_memory = selected_embeddings.mean(dim=1) # [batch * seq_len * num_selected, dim]
# attn_weights = self.attentionpool(selected_embeddings)
# attn_weights = torch.softmax(attn_weights, dim=1)
# pooled_memory = torch.sum(selected_embeddings * attn_weights, dim=1)
selected_memory = pooled_memory.view(bsz, seq_len, num_selected, self.dim) # [batch, seq_len, num_selected, dim]
# 门控MLP融合串型连接h_attn和选中的记忆
memory_output = self.gated_memory_fusion(h_for_memory, selected_memory, memory_scores)
# 残差连接
out = h + memory_output
# 🔍 新增: 计算查找向量与选中记忆条目的余弦相似度
with torch.no_grad():
# 扩展查找向量维度以匹配selected_memory
h_expanded = h_for_memory.unsqueeze(2).expand(-1, -1, num_selected, -1) # [batch, seq_len, num_selected, dim]
# 计算余弦相似度cosine_sim(query, memory) for each selected memory
cosine_similarities = F.cosine_similarity(
h_expanded, # [batch, seq_len, num_selected, dim]
selected_memory, # [batch, seq_len, num_selected, knowledge_dim]
dim=-1 # 在knowledge_dim维度计算余弦相似度
) # [batch, seq_len, num_selected]
# 计算余弦相似度统计信息
cosine_stats = {
'cosine_similarities': cosine_similarities, # [batch, seq_len, num_selected]
'avg_cosine_similarity': cosine_similarities.mean().item(), # 平均余弦相似度
'max_cosine_similarity': cosine_similarities.max().item(), # 最大余弦相似度
'min_cosine_similarity': cosine_similarities.min().item(), # 最小余弦相似度
'std_cosine_similarity': cosine_similarities.std().item(), # 余弦相似度标准差
}
# 收集EMA更新统计信息仅在训练时且启用时
ema_stats = None
if collect_ema_stats and self.training:
ema_stats = {
'memory_indices': memory_indices, # [batch, seq_len, num_selected]
'memory_scores': memory_scores, # [batch, seq_len, num_selected]
'h_for_memory': h_for_memory, # [batch, seq_len, dim]
'selected_memory': selected_memory, # [batch, seq_len, num_selected, knowledge_dim]
}
if collect_ema_stats:
return out, balance_loss, layer_stats, ema_stats, cosine_stats
else:
return out, balance_loss, layer_stats, cosine_stats
class MiniMindLM(PreTrainedModel):
config_class = LMConfig
def __init__(self, params: LMConfig = None):
self.params = params or LMConfig()
super().__init__(self.params)
self.vocab_size, self.n_layers = params.vocab_size, params.n_layers
self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim)
self.dropout = nn.Dropout(params.dropout)
self.layers = nn.ModuleList([MiniMindBlock(l, params) for l in range(self.n_layers)])
self.norm = RMSNorm(params.dim, eps=params.norm_eps)
self.output = nn.Linear(params.dim, params.vocab_size, bias=False)
self.tok_embeddings.weight = self.output.weight
self.register_buffer("pos_cis",
precompute_pos_cis(dim=params.dim // params.n_heads, theta=params.rope_theta),
persistent=False)
# 初始化共享记忆库 - 实验1.4.6存储token_id而非特征向量
# VQ-VAE风格memory_bank作为codebook使用EMA更新而非梯度更新
if params.use_ema_update:
self.memory_bank = nn.Parameter(
torch.randint(0, params.vocab_size, (params.knowledge_num, params.knowledge_length)),
requires_grad=False # 禁用梯度更新使用EMA更新
)
else:
self.memory_bank = nn.Parameter(
torch.randint(0, params.vocab_size, (params.knowledge_num, params.knowledge_length)),
requires_grad=True # 传统梯度更新
)
# EMA更新相关缓冲区
if params.use_ema_update:
# 记录每个memory条目的更新统计
self.register_buffer('ema_update_count', torch.zeros(params.knowledge_num), persistent=False)
# 注意现在memory_bank存储token_id但EMA在特征空间进行所以不需要sum_buffer了
# self.register_buffer('ema_sum_buffer', torch.zeros_like(self.memory_bank), persistent=False)
# EMA更新频率计数器
self.register_buffer('ema_step_counter', torch.zeros(1, dtype=torch.long), persistent=False)
# 记录上一步的记忆库状态,用于计算更新统计
self.register_buffer('prev_memory_bank', torch.zeros_like(self.memory_bank), persistent=False)
# 🔥 新增: 冻结mask - 标记哪些memory_bank条目被冻结不更新
if params.freeze_ratio > 0.0:
freeze_num = int(params.knowledge_num * params.freeze_ratio)
freeze_mask = torch.zeros(params.knowledge_num, dtype=torch.bool)
# 固定冻结前面的条目
freeze_mask[:freeze_num] = True
self.register_buffer('freeze_mask', freeze_mask, persistent=False)
print(f"🔥 Memory bank freezing enabled: {freeze_num}/{params.knowledge_num} entries ({params.freeze_ratio*100:.1f}%) frozen")
else:
self.register_buffer('freeze_mask', torch.zeros(params.knowledge_num, dtype=torch.bool), persistent=False)
print(f"🔥 Memory bank freezing disabled: all entries can be updated")
self.OUT = CausalLMOutputWithPast()
def get_memory_update_stats(self):
"""
计算记忆库更新统计信息
Returns:
update_stats: 包含更新统计的字典
"""
with torch.no_grad():
if hasattr(self, 'prev_memory_bank') and self.prev_memory_bank.numel() > 0:
# 计算L2距离变化
l2_distance = torch.norm(self.memory_bank - self.prev_memory_bank, p=2, dim=-1)
avg_l2_distance = l2_distance.mean().item()
max_l2_distance = l2_distance.max().item()
# 计算余弦相似度
cos_sim = F.cosine_similarity(
self.memory_bank.view(-1),
self.prev_memory_bank.view(-1),
dim=0
).item()
# 计算更新率(发生显著变化的记忆条目比例)
threshold = 0.01 # 更新阈值
updated_memories = (l2_distance > threshold).sum().item()
update_rate = updated_memories / self.memory_bank.size(0)
update_stats = {
'memory_avg_l2_change': avg_l2_distance,
'memory_max_l2_change': max_l2_distance,
'memory_cosine_similarity': cos_sim,
'memory_update_rate': update_rate,
'memory_updated_count': updated_memories
}
else:
# 第一次调用时的默认值
update_stats = {
'memory_avg_l2_change': 0.0,
'memory_max_l2_change': 0.0,
'memory_cosine_similarity': 1.0,
'memory_update_rate': 0.0,
'memory_updated_count': 0
}
# 更新prev_memory_bank
self.prev_memory_bank.copy_(self.memory_bank)
return update_stats
def forward(self,
input_ids: Optional[torch.Tensor] = None,
**args):
"""Forward pass without KV cache support"""
start_pos = args.get('start_pos', 0)
collect_ema_stats = args.get('collect_ema_stats', self.params.use_ema_update and self.training)
h = self.dropout(self.tok_embeddings(input_ids))
pos_cis = self.pos_cis[start_pos:start_pos + input_ids.size(1)]
# 收集所有层的平衡损失和统计信息
total_balance_loss = 0
all_layer_stats = {}
all_ema_stats = {}
all_cosine_stats = {}
for layer_idx, layer in enumerate(self.layers):
if collect_ema_stats:
h, balance_loss, layer_stats, ema_stats, cosine_stats = layer(h, pos_cis, self.memory_bank, self.tok_embeddings, collect_ema_stats=True)
all_ema_stats[f'layer_{layer_idx}'] = ema_stats
else:
h, balance_loss, layer_stats, cosine_stats = layer(h, pos_cis, self.memory_bank, self.tok_embeddings, collect_ema_stats=False)
total_balance_loss += balance_loss
# 为每层的统计信息添加前缀
for key, value in layer_stats.items():
all_layer_stats[f'layer_{layer_idx}_{key}'] = value
# 为每层的余弦相似度统计信息添加前缀
for key, value in cosine_stats.items():
all_cosine_stats[f'layer_{layer_idx}_{key}'] = value
logits = self.output(self.norm(h))
# 使用总的平衡损失作为aux_loss
aux_loss = total_balance_loss
self.OUT.__setitem__('last_hidden_state', h)
self.OUT.__setitem__('logits', logits)
self.OUT.__setitem__('aux_loss', aux_loss)
self.OUT.__setitem__('layer_stats', all_layer_stats) # 添加层级统计信息
self.OUT.__setitem__('ema_stats', all_ema_stats if collect_ema_stats else None) # 添加EMA统计信息
self.OUT.__setitem__('cosine_stats', all_cosine_stats) # 添加余弦相似度统计信息
self.OUT.__setitem__('past_key_values', None) # 不支持KV cache
return self.OUT
@torch.inference_mode()
def generate(self, input_ids, eos_token_id=2, max_new_tokens=1024, temperature=0.75, top_p=0.90,
stream=False, rp=1., pad_token_id=0, num_return_sequences=1, **args):
"""Generate without KV cache"""
# 流式生成
if stream:
return self._stream(input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, **args)
# 直接生成
generated = []
for i in range(input_ids.size(0)):
non_pad = input_ids[i][input_ids[i] != pad_token_id].unsqueeze(0)
for _ in range(num_return_sequences):
out = self._stream(non_pad, eos_token_id, max_new_tokens, temperature, top_p, rp, **args)
tokens_list = [tokens[:, -1:] for tokens in out]
gen = torch.cat(tokens_list, dim=-1) if tokens_list else non_pad
full_sequence = torch.cat([non_pad, gen], dim=-1)
generated.append(full_sequence)
max_length = max(seq.size(1) for seq in generated)
generated = [
torch.cat(
[seq, torch.full((1, max_length - seq.size(1)), pad_token_id, dtype=seq.dtype, device=seq.device)],
dim=-1)
for seq in generated
]
output = torch.cat(generated, dim=0)
res = output.view(input_ids.size(0) * num_return_sequences, -1)
return res
def _stream(self, input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, **args):
"""Stream generation without KV cache - regenerates full sequence each time"""
start = input_ids.shape[1]
while input_ids.shape[1] < start + max_new_tokens:
# 每次都重新计算整个序列因为没有KV cache
out = self(input_ids, **args)
logits = out.logits[:, -1, :]
# 重复惩罚
logits[:, list(set(input_ids.tolist()[0]))] /= rp
logits /= (temperature + 1e-9)
# Top-p采样
if top_p is not None and top_p < 1.0:
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
sorted_probs = F.softmax(sorted_logits, dim=-1)
cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
sorted_indices_to_remove[:, 0] = False
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
logits[indices_to_remove] = -float('Inf')
input_ids_next = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
input_ids = torch.cat((input_ids, input_ids_next), dim=1)
yield input_ids[:, start:]
if input_ids_next.item() == eos_token_id:
break
def apply_ema_update(self, ema_stats):
"""
应用token-based EMA更新到memory_bank
实验1.4.6批量化tensor操作优化版本
Args:
ema_stats: 从forward pass收集的EMA统计信息格式为
{'layer_0': {'memory_indices': ..., 'h_for_memory': ...}, 'layer_1': ...}
"""
if not self.params.use_ema_update:
return {}
# 增加EMA步数计数器
self.ema_step_counter += 1
# 检查是否需要进行EMA更新
if self.ema_step_counter % self.params.ema_update_freq != 0:
return {'ema_update_applied': False, 'reason': 'frequency_check_failed'}
with torch.no_grad():
device = self.memory_bank.device
knowledge_num, knowledge_length = self.memory_bank.shape
dim = self.params.dim
# 🚀 批量收集所有层的数据(避免字典操作)
all_indices = []
all_features = []
total_selections = 0
total_layers = 0
# 收集所有层的EMA统计信息
for layer_ema_stats in ema_stats.values():
if layer_ema_stats is None:
continue
total_layers += 1
memory_indices = layer_ema_stats['memory_indices'] # [batch, seq_len, num_selected]
h_for_memory = layer_ema_stats['h_for_memory'] # [batch, seq_len, dim]
bsz, seq_len, num_selected = memory_indices.shape
total_selections += bsz * seq_len * num_selected
# 展平索引和对应的h_for_memory
flat_indices = memory_indices.view(-1) # [batch * seq_len * num_selected]
# 为每个选择位置复制对应的h_for_memory
h_expanded = h_for_memory.unsqueeze(2).expand(-1, -1, num_selected, -1) # [batch, seq_len, num_selected, dim]
flat_h = h_expanded.reshape(-1, dim) # [batch * seq_len * num_selected, dim]
all_indices.append(flat_indices)
all_features.append(flat_h)
if not all_indices:
return {'ema_update_applied': False, 'reason': 'no_ema_stats'}
# 🚀 合并所有数据
all_indices = torch.cat(all_indices, dim=0) # [total_selections]
all_features = torch.cat(all_features, dim=0) # [total_selections, dim]
# 🚀 批量计算每个memory的平均特征避免循环
unique_indices, inverse_indices = torch.unique(all_indices, return_inverse=True)
# 使用scatter_add批量聚合确保数据类型一致
aggregated_features = torch.zeros(unique_indices.size(0), dim, device=device, dtype=all_features.dtype)
count_per_memory = torch.zeros(unique_indices.size(0), device=device, dtype=all_features.dtype)
aggregated_features.scatter_add_(0, inverse_indices.unsqueeze(1).expand(-1, dim), all_features)
count_per_memory.scatter_add_(0, inverse_indices, torch.ones_like(inverse_indices, dtype=all_features.dtype))
# 计算平均值
avg_features = aggregated_features / count_per_memory.unsqueeze(1) # [unique_count, dim]
# 🚀 分批EMA更新控制显存使用
batch_size = 4096 # 每批处理4096个memory控制显存
updated_memories = 0
for i in range(0, unique_indices.size(0), batch_size):
end_i = min(i + batch_size, unique_indices.size(0))
batch_indices = unique_indices[i:end_i]
batch_avg_features = avg_features[i:end_i]
# 当前批次的token解码
current_tokens_batch = self.memory_bank[batch_indices] # [batch_size, knowledge_length]
current_embeddings_batch = self.tok_embeddings(current_tokens_batch.view(-1)).view(
batch_indices.size(0), knowledge_length, dim) # [batch_size, knowledge_length, dim]
old_features_batch = current_embeddings_batch.view(batch_indices.size(0), -1) # [batch_size, knowledge_length * dim]
expanded_new_features = batch_avg_features.repeat(1, knowledge_length) # [batch_size, knowledge_length * dim]
# EMA更新new = γ * old + (1-γ) * new_avg
updated_features_batch = (
self.params.ema_decay * old_features_batch +
(1 - self.params.ema_decay) * expanded_new_features
)
# 分批编码为token_ids关键控制输出层的输入大小
updated_reshaped = updated_features_batch.view(-1, dim) # [batch_size * knowledge_length, dim]
logits_batch = self.output(updated_reshaped) # [batch_size * knowledge_length, vocab_size]
new_token_ids_batch = torch.argmax(logits_batch, dim=-1).view(batch_indices.size(0), knowledge_length)
# 🔥 新增: 应用冻结mask只更新未冻结的条目
# 检查哪些batch_indices对应的条目没有被冻结
unfrozen_mask_batch = ~self.freeze_mask[batch_indices] # [batch_size] - True表示未冻结
# 只更新未冻结的条目
if unfrozen_mask_batch.any():
unfrozen_indices = batch_indices[unfrozen_mask_batch]
unfrozen_tokens = new_token_ids_batch[unfrozen_mask_batch]
self.memory_bank[unfrozen_indices] = unfrozen_tokens
updated_memories += unfrozen_indices.size(0)
else:
# 如果这个batch中的所有条目都被冻结则跳过更新
pass
update_ratio = updated_memories / knowledge_num
# 🔥 新增: 计算冻结统计信息
frozen_count = self.freeze_mask.sum().item()
total_memories = knowledge_num
update_stats = {
'ema_update_applied': True,
'ema_step': self.ema_step_counter.item(),
'total_selections': total_selections,
'total_layers': total_layers,
'updated_memories': updated_memories,
'update_ratio': update_ratio,
'frozen_memories': frozen_count,
'frozen_ratio': frozen_count / total_memories,
'ema_decay': self.params.ema_decay,
'selected_memory_coverage': updated_memories / knowledge_num,
}
return update_stats

View File

@ -1,414 +0,0 @@
#!/bin/bash
# ============================================================================
# MiniMind 实验脚本 - Experiment 1.4.10
# ============================================================================
#
# 🎯 实验目标:
# 基于实验1.4.9实现四损失系统CE + Balance + Similarity + Diversity
# 核心创新Gumbel-Softmax选择机制 + 可微分相似度损失 + 候选集多样性约束
#
# 使用方法:
# bash run_file/experiment_1_4_10.sh
# ============================================================================
# ----------------------------------------------------------------------------
# 🧑‍🔬 实验基本信息
# ----------------------------------------------------------------------------
EXPERIMENT_VERSION="1.4.10"
EXPERIMENT_DESCRIPTION="四损失系统实验 - Gumbel-Softmax + 可微分相似度损失 + 多样性约束"
RESEARCHER_NAME="AI Assistant"
EXPERIMENT_DATE="$(date '+%Y-%m-%d %H:%M:%S')"
# ----------------------------------------------------------------------------
# 🤖 环境配置
# ----------------------------------------------------------------------------
# 调试和监控环境变量
export NCCL_DEBUG=INFO
export PYTHONFAULTHANDLER=1
export CUDA_LAUNCH_BLOCKING=1
# SwanLab 配置
export SWANLAB_PROJECT="MiniMind-Experiment-1.4.10"
# 日志配置
LOG_DIR="out/experiment_${EXPERIMENT_VERSION}"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/experiment.log"
# ----------------------------------------------------------------------------
# 🤖 硬件配置
# ----------------------------------------------------------------------------
CUDA_VISIBLE_DEVICES="0,1,2,3"
NUM_PROCESSES="4"
MIXED_PRECISION="bf16"
MAIN_PROCESS_PORT="29500"
# ----------------------------------------------------------------------------
# 🤖 模型架构参数
# ----------------------------------------------------------------------------
MODEL_TYPE="model_memory" # 🔥 使用Token-based Memory模型
MODEL_SIZE="50.0"
DIM="512"
N_LAYERS="16"
N_HEADS="32"
MAX_SEQ_LEN="512"
USE_MOE="false"
# 🔥 知识库配置(四损失系统优化)
KNOWLEDGE_NUM="1048576" # 1M entries
KNOWLEDGE_LENGTH="8" # 🔥 增加到32个token提升表达能力
KNOWLEDGE_DIM="128" # 保留兼容性
DISABLE_DB="false"
# ----------------------------------------------------------------------------
# 🤖 训练超参数
# ----------------------------------------------------------------------------
EPOCHS="3"
EMBEDDING_EPOCH="42"
BATCH_SIZE="4" # 🔥 降低批次大小以适应更复杂的计算
ACCUMULATION_STEPS="4" # 🔥 增加累积步数保持有效批次大小
LEARNING_RATE="2e-4" # 🔥 适度降低学习率提升稳定性
DTYPE="bfloat16"
GRAD_CLIP="1.0"
WARMUP_ITERS="0"
# 🔥 四损失系统配置
BALANCE_LOSS_COEF="0.01" # 平衡损失系数
SIMILARITY_LOSS_COEF="0.15" # 🔥 相似度损失系数(核心损失)
DIVERSITY_LOSS_COEF="0.08" # 🔥 多样性损失系数(避免候选重复)
# 数据和缓存路径
DATA_PATH="/home/zym/Code/stable/merged_pretrain.jsonl"
DATABASE_INIT_PATH="/home/zym/Code/stable/sentence_trex_data.json"
CLUSTER_CACHE_PATH="None" # 禁用聚类缓存
VAL_DATA_PATH="dataset/stable/eval_data.json"
# 训练配置
NUM_WORKERS="8"
LOG_INTERVAL="100" # 🔥 更频繁的日志记录观察四个损失
VAL_INTERVAL="100"
SAVE_INTERVAL="10000"
# 性能分析配置
USE_PROFILE="true"
PROFILE_INTERVAL="10"
MEMORY_MONITOR_INTERVAL="100"
# 高级功能
USE_FLASH_ATTN="true"
FAST_CLUSTERING="true"
# 冻结率
FREEZE_RATIO="0.2"
# ----------------------------------------------------------------------------
# 🤖 预检查函数
# ----------------------------------------------------------------------------
check_environment() {
echo "🔍 环境检查中..."
# 检查GPU可用性
if ! nvidia-smi &> /dev/null; then
echo "❌ 错误: 未检测到GPU或nvidia-smi不可用"
exit 1
fi
# 检查CUDA设备
if ! nvidia-smi -i "$CUDA_VISIBLE_DEVICES" &> /dev/null; then
echo "❌ 错误: GPU $CUDA_VISIBLE_DEVICES 不可用"
exit 1
fi
# 检查数据文件
if [[ ! -f "$DATA_PATH" ]]; then
echo "❌ 错误: 训练数据文件不存在: $DATA_PATH"
exit 1
fi
if [[ ! -f "$DATABASE_INIT_PATH" ]]; then
echo "❌ 错误: 数据库初始化文件不存在: $DATABASE_INIT_PATH"
exit 1
fi
echo "✅ 环境检查通过"
}
# ----------------------------------------------------------------------------
# 🤖 实验信息记录
# ----------------------------------------------------------------------------
log_experiment_info() {
echo "📝 记录实验信息..."
cat > "$LOG_DIR/experiment_info.txt" << EOF
========================================
MiniMind 实验信息
========================================
实验版本: $EXPERIMENT_VERSION
实验描述: $EXPERIMENT_DESCRIPTION
研究者: $RESEARCHER_NAME
开始时间: $EXPERIMENT_DATE
========================================
硬件配置:
GPU设备: $CUDA_VISIBLE_DEVICES
进程数: $NUM_PROCESSES
混合精度: $MIXED_PRECISION
========================================
模型配置:
模型类型: $MODEL_TYPE (Token-based Memory + 四损失系统)
模型大小: $MODEL_SIZE MB
维度: $DIM
层数: $N_LAYERS
注意力头数: $N_HEADS
最大序列长度: $MAX_SEQ_LEN
知识库大小: $KNOWLEDGE_NUM (1M entries)
知识长度: $KNOWLEDGE_LENGTH (增强表达能力)
知识维度: $KNOWLEDGE_DIM (兼容性保留)
========================================
训练配置:
训练轮次: $EPOCHS
批次大小: $BATCH_SIZE (优化显存使用)
学习率: $LEARNING_RATE (稳定性优化)
梯度累积: $ACCUMULATION_STEPS (保持有效批次)
数据类型: $DTYPE
========================================
🔥 四损失系统配置:
平衡损失系数: $BALANCE_LOSS_COEF (记忆选择平衡)
相似度损失系数: $SIMILARITY_LOSS_COEF (语义匹配优化)
多样性损失系数: $DIVERSITY_LOSS_COEF (候选集多样性)
========================================
🔥 Gumbel-Softmax配置:
候选项数量: 32 (Product Key生成)
选择数量: 1 (Gumbel-Softmax选择最佳)
温度参数: 1.0 (平衡探索与利用)
选择机制: 硬选择 + Straight-Through Estimator
========================================
🔥 核心创新对比:
传统方法: 16个记忆平均融合 (缺乏语义针对性)
新方法: 32候选→1最佳 (语义相似度驱动)
旧相似度损失: no_grad计算 (不可微分)
新相似度损失: 可微分优化 (直接指导学习)
新增多样性: 候选集内部差异性约束
========================================
数据路径:
训练数据: $DATA_PATH
验证数据: $VAL_DATA_PATH
数据库初始化: $DATABASE_INIT_PATH
聚类缓存: $CLUSTER_CACHE_PATH
========================================
预期改进:
1. 相似度损失收敛: 从震荡→稳定下降
2. 记忆选择质量: 更精准的语义匹配
3. 生成文本质量: 更好的连贯性和相关性
4. 四损失平衡: CE主导其他损失辅助
========================================
EOF
}
# ----------------------------------------------------------------------------
# 🤖 主执行函数
# ----------------------------------------------------------------------------
run_experiment() {
echo "🚀 开始执行实验 $EXPERIMENT_VERSION"
echo "📄 实验描述: $EXPERIMENT_DESCRIPTION"
echo "⏰ 开始时间: $EXPERIMENT_DATE"
# 构建训练命令
local train_cmd="CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES accelerate launch --config_file accelerate_config.yaml train_pretrain_accelerate.py"
# 添加训练参数
train_cmd+=" --out_dir \"$LOG_DIR\""
train_cmd+=" --epochs $EPOCHS"
train_cmd+=" --embedding_epoch $EMBEDDING_EPOCH"
train_cmd+=" --batch_size $BATCH_SIZE"
train_cmd+=" --learning_rate $LEARNING_RATE"
train_cmd+=" --dtype $DTYPE"
train_cmd+=" --num_workers $NUM_WORKERS"
train_cmd+=" --accumulation_steps $ACCUMULATION_STEPS"
train_cmd+=" --grad_clip $GRAD_CLIP"
train_cmd+=" --warmup_iters $WARMUP_ITERS"
train_cmd+=" --log_interval $LOG_INTERVAL"
train_cmd+=" --val_interval $VAL_INTERVAL"
train_cmd+=" --save_interval $SAVE_INTERVAL"
train_cmd+=" --dim $DIM"
train_cmd+=" --n_layers $N_LAYERS"
train_cmd+=" --n_heads $N_HEADS"
train_cmd+=" --max_seq_len $MAX_SEQ_LEN"
train_cmd+=" --data_path \"$DATA_PATH\""
train_cmd+=" --val_data_path \"$VAL_DATA_PATH\""
train_cmd+=" --knowledge_num $KNOWLEDGE_NUM"
train_cmd+=" --knowledge_length $KNOWLEDGE_LENGTH"
train_cmd+=" --database_init_path \"$DATABASE_INIT_PATH\""
train_cmd+=" --memory_monitor_interval $MEMORY_MONITOR_INTERVAL"
train_cmd+=" --model_type \"$MODEL_TYPE\""
train_cmd+=" --model_size $MODEL_SIZE"
train_cmd+=" --freeze_ratio $FREEZE_RATIO"
# 🔥 四损失系统参数
train_cmd+=" --balance_loss_coef $BALANCE_LOSS_COEF"
train_cmd+=" --similarity_loss_coef $SIMILARITY_LOSS_COEF"
train_cmd+=" --diversity_loss_coef $DIVERSITY_LOSS_COEF"
# 可选参数
if [[ "$USE_PROFILE" == "true" ]]; then
train_cmd+=" --profile"
train_cmd+=" --profile_interval $PROFILE_INTERVAL"
fi
if [[ "$USE_FLASH_ATTN" == "true" ]]; then
train_cmd+=" --use_flash_attn"
fi
if [[ "$FAST_CLUSTERING" == "true" ]]; then
train_cmd+=" --fast_clustering"
fi
if [[ "$CLUSTER_CACHE_PATH" != "None" ]]; then
train_cmd+=" --cluster_cache_path \"$CLUSTER_CACHE_PATH\""
fi
# SwanLab配置
train_cmd+=" --use_swanlab"
train_cmd+=" --swanlab_project \"$SWANLAB_PROJECT\""
# train_cmd+=" --swanlab_online True"
echo "📋 执行命令:"
echo "$train_cmd"
echo
# 记录命令到日志文件
echo "执行命令: $train_cmd" >> "$LOG_FILE"
echo "开始时间: $(date)" >> "$LOG_FILE"
# 使用nohup执行训练后台运行输出写入日志文件
echo "🔄 使用nohup后台运行训练输出将写入日志文件: $LOG_FILE"
# 创建训练脚本
train_script="/tmp/train_${EXPERIMENT_VERSION}.sh"
cat > "$train_script" << EOF
#!/bin/bash
# cd /home/pci/nas/AI_Large_Model_Team/ycz/Minimind
# source .venv/bin/activate
$train_cmd
echo "结束时间: \$(date)"
echo "退出代码: \$?"
EOF
chmod +x "$train_script"
# 使用nohup后台运行
nohup bash "$train_script" >> "$LOG_FILE" 2>&1 &
local train_pid=$!
echo "🔥 训练进程已启动PID: $train_pid"
echo "训练PID: $train_pid" >> "$LOG_FILE"
echo "训练脚本: $train_script" >> "$LOG_FILE"
# 等待几秒确保进程启动
sleep 5
# 检查进程是否还在运行
if kill -0 $train_pid 2>/dev/null; then
echo "✅ 训练进程正在后台运行"
echo "📋 实时查看日志: tail -f $LOG_FILE"
echo "📋 检查进程状态: ps -p $train_pid"
echo "🛑 停止训练: kill $train_pid"
echo "📈 SwanLab: https://swanlab.cn/project/$SWANLAB_PROJECT"
echo ""
echo "🧠 四损失系统机制正在测试中..."
echo " 🔥 损失结构: CE + Balance + Similarity + Diversity"
echo " 🔥 候选机制: 32个候选 → Gumbel-Softmax选择1个最佳"
echo " 🔥 相似度损失: 可微分优化 (修复震荡问题)"
echo " 🔥 多样性约束: 候选集内部差异性正则化"
echo " 🔥 选择策略: 语义相似度驱动 vs 随机平均"
echo ""
echo "📊 与实验1.4.9对比:"
echo " - 选择机制: 平均融合 → 最优选择"
echo " - 相似度损失: 不可微分 → 可微分"
echo " - 候选多样性: 无约束 → 多样性正则化"
echo " - 损失系统: 三损失 → 四损失平衡"
echo ""
echo "训练正在后台运行,可以安全关闭终端。"
echo ""
echo "🎯 预期改进:"
echo " - 相似度损失: 稳定收敛 (不再震荡)"
echo " - CE Loss: < 0.8 (改善语言建模)"
echo " - 生成质量: 更连贯的文本输出"
echo " - 记忆选择: 更精准的语义匹配"
echo ""
echo "⏱️ 预计训练时间: 18-22小时 (额外计算开销)"
echo "📊 预计GPU占用: ~24GB (Gumbel-Softmax + 多样性计算)"
echo ""
echo "🔍 关键监控指标:"
echo " - Similarity Loss: 期望从1.9震荡→稳定下降"
echo " - Diversity Loss: 保持适中值避免过度惩罚"
echo " - Selection Entropy: 监控选择多样性"
echo " - Selected Similarity: 观察选中记忆的相似度"
echo ""
else
echo "❌ 训练进程启动失败"
echo "📋 查看日志: $LOG_FILE"
exit 1
fi
}
# ----------------------------------------------------------------------------
# 🤖 清理函数
# ----------------------------------------------------------------------------
cleanup() {
echo "🧹 清理临时文件..."
# 删除临时验证文件
rm -f /tmp/temp_val.jsonl
}
# ----------------------------------------------------------------------------
# 🤖 信号处理
# ----------------------------------------------------------------------------
trap cleanup EXIT
trap 'echo "❌ 实验被中断"; cleanup; exit 130' INT TERM
# ----------------------------------------------------------------------------
# 🤖 主程序入口
# ----------------------------------------------------------------------------
main() {
echo "============================================================================"
echo "🧠 MiniMind 预训练实验 1.4.10"
echo "🎯 四损失系统 - Gumbel-Softmax + 可微分相似度损失 + 多样性约束"
echo "============================================================================"
echo ""
echo "🔥 核心创新:"
echo " ► 四损失架构: CE + Balance + Similarity + Diversity"
echo " ► Gumbel-Softmax: 32候选→1最佳 (可微分离散选择)"
echo " ► 相似度损失: 可微分优化 (修复震荡)"
echo " ► 多样性约束: 候选集内部差异性正则化"
echo " ► 语义选择: 相似度驱动 vs 平均融合"
echo ""
echo "🎯 实验假设:"
echo " ✓ 可微分相似度损失解决震荡问题"
echo " ✓ 语义驱动选择改善记忆利用质量"
echo " ✓ 多样性约束防止候选集退化"
echo " ✓ 四损失平衡提升整体模型性能"
echo ""
echo "🔧 关键技术细节:"
echo " ► Straight-Through Estimator确保梯度流"
echo " ► 候选集多样性通过余弦相似度矩阵计算"
echo " ► Gumbel噪声增强选择随机性"
echo " ► 硬选择保持离散性,软梯度保持可微性"
echo ""
echo "============================================================================"
# 执行检查和初始化
check_environment
log_experiment_info
# 运行实验
run_experiment
echo "============================================================================"
echo "✅ 实验 $EXPERIMENT_VERSION 启动完成"
echo "📅 启动时间: $(date)"
echo "============================================================================"
}
# 执行主程序
main "$@"

View File

@ -37,13 +37,9 @@ EXPERIMENT_DATE="$(date '+%Y-%m-%d %H:%M:%S')" # 自动记录实验开始时间
# source "$VIRTUAL_ENV/bin/activate" # source "$VIRTUAL_ENV/bin/activate"
# 调试和监控环境变量 # 调试和监控环境变量
export NCCL_DEBUG=INFO # NCCL 调试信息
export PYTHONFAULTHANDLER=1 # Python 故障处理 export PYTHONFAULTHANDLER=1 # Python 故障处理
# export NCCL_DEBUG=INFO # NCCL 调试信息(仅调试时启用) export CUDA_LAUNCH_BLOCKING=1 # CUDA 同步执行(调试用)
# export CUDA_LAUNCH_BLOCKING=1 # CUDA 同步执行(严重影响性能,仅调试时启用)
# 🔥 强制禁用输出缓冲确保日志立即写入不影响GPU性能
export PYTHONUNBUFFERED=1 # Python 解释器不缓冲输出
export PYTHONIOENCODING=utf-8 # 确保编码一致性
# SwanLab 配置 # SwanLab 配置
export SWANLAB_API_KEY="[SWANLAB_API_KEY]" # 🤖 [AI构建] SwanLab API密钥 export SWANLAB_API_KEY="[SWANLAB_API_KEY]" # 🤖 [AI构建] SwanLab API密钥
@ -296,8 +292,8 @@ echo "退出代码: \$?"
EOF EOF
chmod +x "$train_script" chmod +x "$train_script"
# 使用nohup后台运行并使用stdbuf禁用缓冲 # 使用nohup后台运行
nohup stdbuf -oL -eL bash "$train_script" >> "$LOG_FILE" 2>&1 & nohup bash "$train_script" >> "$LOG_FILE" 2>&1 &
local train_pid=$! local train_pid=$!
echo "🔥 训练进程已启动PID: $train_pid" echo "🔥 训练进程已启动PID: $train_pid"

View File

@ -1,10 +1,6 @@
import os import os
# 设置环境变量 - 将wandb替换为SwanLab # 设置环境变量 - 将wandb替换为SwanLab
# os.environ["SWANLAB_MODE"] = "online" # SwanLab使用在线模式 # os.environ["SWANLAB_MODE"] = "online" # SwanLab使用在线模式
# 🔥 强制禁用输出缓冲,确保日志立即写入
os.environ['PYTHONUNBUFFERED'] = '1' # Python 解释器不缓冲输出
os.environ['PYTHONIOENCODING'] = 'utf-8' # 确保编码一致性
import platform import platform
import argparse import argparse
from tqdm import tqdm from tqdm import tqdm
@ -96,9 +92,7 @@ def log_memory_status(step, prefetch_batches, accelerator, stage="", detailed=Fa
def Logger(msg, accelerator=None): def Logger(msg, accelerator=None):
# 如果没有提供accelerator则只在主进程打印 # 如果没有提供accelerator则只在主进程打印
if accelerator is None or accelerator.is_main_process: if accelerator is None or accelerator.is_main_process:
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {msg}", flush=True) # 强制刷新输出缓冲 print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {msg}")
import sys
sys.stdout.flush() # 确保立即写入
# Helper function to format seconds into HH:MM:SS # Helper function to format seconds into HH:MM:SS
def format_time(seconds): def format_time(seconds):
@ -1009,42 +1003,25 @@ def train_epoch(epoch, accelerator, model, train_loader, optimizer, scheduler, a
).view(Y.size()) ).view(Y.size())
ce_loss = (ce_loss * loss_mask).sum() / loss_mask.sum() ce_loss = (ce_loss * loss_mask).sum() / loss_mask.sum()
# 🔥 实验1.4.9: 四损失系统处理 # 获取平衡损失(如果模型支持)
balance_loss = 0 balance_loss = 0
similarity_loss = 0
diversity_loss = 0
if hasattr(res, 'aux_loss') and res.aux_loss is not None: if hasattr(res, 'aux_loss') and res.aux_loss is not None:
aux_loss = res.aux_loss balance_loss = res.aux_loss
if isinstance(aux_loss, dict):
# 新的四损失结构
balance_loss = aux_loss.get('balance_loss', 0)
similarity_loss = aux_loss.get('similarity_loss', 0)
diversity_loss = aux_loss.get('diversity_loss', 0)
else:
# 向后兼容旧的单一aux_loss
balance_loss = aux_loss
# 获取余弦相似度统计信息(如果模型支持) # 获取余弦相似度统计信息(如果模型支持)
cosine_stats = {} cosine_stats = {}
avg_selected_similarity = 0.0
if hasattr(res, 'cosine_stats') and res.cosine_stats is not None: if hasattr(res, 'cosine_stats') and res.cosine_stats is not None:
cosine_stats = res.cosine_stats cosine_stats = res.cosine_stats
# 🔥 使用选中记忆的平均相似度(更精确的指标) # 计算平均余弦相似度
selected_similarities = [v for k, v in cosine_stats.items() if k.endswith('_selected_avg_similarity')] avg_cosine_similarity = 0.0
if selected_similarities: if cosine_stats:
avg_selected_similarity = np.mean(selected_similarities) # 计算所有层的平均余弦相似度
cosine_similarities = [v for k, v in cosine_stats.items() if k.endswith('_avg_cosine_similarity')]
if cosine_similarities:
avg_cosine_similarity = np.mean(cosine_similarities)
# 🔥 四损失系统CE + Balance + Similarity + Diversity # 计算总损失
# 损失系数可以通过命令行参数调整 total_loss = ce_loss + args.balance_loss_coef * balance_loss + 2 * (1-avg_cosine_similarity)
balance_coef = getattr(args, 'balance_loss_coef', 0.01)
similarity_coef = getattr(args, 'similarity_loss_coef', 0.1)
diversity_coef = getattr(args, 'diversity_loss_coef', 0.05)
total_loss = (ce_loss +
balance_coef * balance_loss +
similarity_coef * similarity_loss +
diversity_coef * diversity_loss)
loss = total_loss / args.accumulation_steps loss = total_loss / args.accumulation_steps
# 计时前向传播结束 (只在主进程进行) # 计时前向传播结束 (只在主进程进行)
@ -1243,15 +1220,13 @@ def train_epoch(epoch, accelerator, model, train_loader, optimizer, scheduler, a
layer_stats = res.layer_stats layer_stats = res.layer_stats
# 🔥 构建四损失系统的日志字典 # 构建日志字典
log_dict = { log_dict = {
"epoch": epoch + 1, "epoch": epoch + 1,
"step": step + 1, "step": step + 1,
"total_steps_in_epoch": total_steps_in_epoch, "total_steps_in_epoch": total_steps_in_epoch,
"train/loss_ce": ce_loss.item(), "train/loss_ce": ce_loss.item(),
"train/loss_balance": balance_loss.item() if isinstance(balance_loss, torch.Tensor) else balance_loss, "train/loss_balance": balance_loss.item() if isinstance(balance_loss, torch.Tensor) else balance_loss,
"train/loss_similarity": similarity_loss.item() if isinstance(similarity_loss, torch.Tensor) else similarity_loss,
"train/loss_diversity": diversity_loss.item() if isinstance(diversity_loss, torch.Tensor) else diversity_loss,
"train/loss_total": total_loss.item(), "train/loss_total": total_loss.item(),
"lr": current_lr, "lr": current_lr,
"tokens_per_sec": tokens_per_sec, "tokens_per_sec": tokens_per_sec,
@ -1280,20 +1255,17 @@ def train_epoch(epoch, accelerator, model, train_loader, optimizer, scheduler, a
'memory/avg_coverage_rate': avg_coverage, 'memory/avg_coverage_rate': avg_coverage,
'memory/total_dead_memories': total_dead, 'memory/total_dead_memories': total_dead,
'memory/total_hot_memories': total_hot, 'memory/total_hot_memories': total_hot,
'train/avg_selected_similarity': avg_selected_similarity, # 🔥 使用选中记忆的相似度 'train/avg_cosine_similarity': avg_cosine_similarity,
}) })
# 🔥 四损失系统的控制台输出
Logger(f"Epoch {epoch+1}/{args.epochs}, Step {step+1}/{total_steps_in_epoch}, " Logger(f"Epoch {epoch+1}/{args.epochs}, Step {step+1}/{total_steps_in_epoch}, "
f"CE: {log_dict['train/loss_ce']:.4f}, " f"CE Loss: {log_dict['train/loss_ce']:.4f}, "
f"Bal: {log_dict['train/loss_balance']:.4f}, " f"Balance Loss: {log_dict['train/loss_balance']:.4f}, "
f"Sim: {log_dict['train/loss_similarity']:.4f}, " f"Avg Cosine Sim: {avg_cosine_similarity:.4f}, "
f"Div: {log_dict['train/loss_diversity']:.4f}, " f"Total Loss: {log_dict['train/loss_total']:.4f}, "
f"Total: {log_dict['train/loss_total']:.4f}, " f"Val Loss: {log_dict.get('val/loss', 'N/A')}, "
f"Val: {log_dict.get('val/loss', 'N/A')}, "
f"LR: {log_dict['lr']:.6f}, " f"LR: {log_dict['lr']:.6f}, "
f"Speed: {log_dict['tokens_per_sec']:.2f} tokens/sec | " f"Speed: {log_dict['tokens_per_sec']:.2f} tokens/sec | "
f"Sel.Sim: {avg_selected_similarity:.4f} | "
f"Epoch Time Left: {format_time(epoch_remaining_time)} | " f"Epoch Time Left: {format_time(epoch_remaining_time)} | "
f"Total Time Left: {format_time(total_remaining_time)}", accelerator) f"Total Time Left: {format_time(total_remaining_time)}", accelerator)
@ -1376,7 +1348,7 @@ def main():
parser.add_argument("--knowledge_dim", type=int, default=128,help="知识库的向量维度") parser.add_argument("--knowledge_dim", type=int, default=128,help="知识库的向量维度")
parser.add_argument("--database_init_path", type=str, default="/home/iomgaa/Code/Minimind/dataset/stable/sentence_trex_data.json", help="数据库初始化路径") parser.add_argument("--database_init_path", type=str, default="/home/iomgaa/Code/Minimind/dataset/stable/sentence_trex_data.json", help="数据库初始化路径")
parser.add_argument("--fast_clustering", action="store_true", default=True, help="使用快速近似聚类算法(适用于大数据集)") parser.add_argument("--fast_clustering", action="store_true", default=True, help="使用快速近似聚类算法(适用于大数据集)")
parser.add_argument("--cluster_cache_path", type=str, default="./cache/cluster_tokens_single.pt", help="聚类结果缓存文件路径") parser.add_argument("--cluster_cache_path", type=str, default="/home/iomgaa/Code/Minimind/cache/cluster_tokens_single.pt", help="聚类结果缓存文件路径")
parser.add_argument("--recompute_clusters", action="store_true", default=False, help="强制重新计算聚类,忽略缓存文件") parser.add_argument("--recompute_clusters", action="store_true", default=False, help="强制重新计算聚类,忽略缓存文件")
parser.add_argument("--memory_monitor", action="store_true", default=False, help="启用内存监控") parser.add_argument("--memory_monitor", action="store_true", default=False, help="启用内存监控")
parser.add_argument("--memory_monitor_interval", type=int, default=10, help="内存监控间隔(步数)") parser.add_argument("--memory_monitor_interval", type=int, default=10, help="内存监控间隔(步数)")
@ -1384,11 +1356,8 @@ def main():
parser.add_argument("--model_size", type=float, default=50.0, help="模型大小") parser.add_argument("--model_size", type=float, default=50.0, help="模型大小")
parser.add_argument("--swanlab_online", type=bool, default=False, help="是否使用在线SwanLab服务") parser.add_argument("--swanlab_online", type=bool, default=False, help="是否使用在线SwanLab服务")
parser.add_argument("--balance_loss_coef", type=float, default=0.01, help="平衡损失系数") parser.add_argument("--balance_loss_coef", type=float, default=0.01, help="平衡损失系数")
parser.add_argument("--similarity_loss_coef", type=float, default=0.1, help="相似度损失系数实验1.4.9")
parser.add_argument("--diversity_loss_coef", type=float, default=0.05, help="多样性损失系数实验1.4.9")
parser.add_argument("--val_data_path", type=str, default="/home/zym/Code/stable/eval_data.json", help="验证数据集路径") parser.add_argument("--val_data_path", type=str, default="/home/zym/Code/stable/eval_data.json", help="验证数据集路径")
parser.add_argument("--val_interval", type=int, default=100, help="验证评估间隔") parser.add_argument("--val_interval", type=int, default=100, help="验证评估间隔")
parser.add_argument("--freeze_ratio", type=float, default=0.2, help="冻结率")
args = parser.parse_args() args = parser.parse_args()
######################################################### #########################################################
@ -1427,8 +1396,7 @@ def main():
flash_attn=args.use_flash_attn, flash_attn=args.use_flash_attn,
knowledge_num=args.knowledge_num, knowledge_num=args.knowledge_num,
knowledge_length=args.knowledge_length, knowledge_length=args.knowledge_length,
embeddings_epoch=args.embedding_epoch, embeddings_epoch=args.embedding_epoch
freeze_ratio=args.freeze_ratio
) )
######################################################### #########################################################