Home / Market / episodic-memory-debugger

episodic-memory-debugger

Provides tools for debugging episodic memory systems including recall precision analysis, multi-modal encoding validation, indexing efficiency checks, and ir...

skill★ 00 dlclawhubMIT-0Install in CosmosUpstream Source

Documentation & Preview

/**

*

*

*/

/**

*/ class RecallPrecisionAnalyzer { constructor() { this.metrics = { totalQueries: 0, relevantRetrievals: 0, irrelevantRetrievals: 0, missedRelevant: 0 }; }

/**

*/ analyzeRecallPrecision(memories, queries, groundTruth) { const results = { overallPrecision: 0, overallRecall: 0, f1Score: 0, perQueryMetrics: [], issues: [] };

let totalRelevant = 0; let totalRetrieved = 0; let totalRelevantRetrieved = 0;

for (const query of queries) { const queryId = query.id || query.text; const relevantIds = groundTruth[queryId] || []; const retrievedIds = query.results?.map(r => r.id) || [];

const relevantRetrieved = retrievedIds.filter(id => relevantIds.includes(id)); const precision = retrievedIds.length > 0 ? relevantRetrieved.length / retrievedIds.length : 0; const recall = relevantIds.length > 0 ? relevantRetrieved.length / relevantIds.length : 0; const f1 = precision + recall > 0 ? 2 * (precision * recall) / (precision + recall) : 0;

totalRelevant += relevantIds.length; totalRetrieved += retrievedIds.length; totalRelevantRetrieved += relevantRetrieved.length;

results.perQueryMetrics.push({ queryId, precision, recall, f1, retrievedCount: retrievedIds.length, relevantCount: relevantIds.length, relevantRetrieved: relevantRetrieved.length });

// Detect issues if (precision < 0.5) { results.issues.push({ type: 'low_precision', queryId, value: precision, message: Low precision (${(precision * 100).toFixed(1)}%) - too many irrelevant results }); }

if (recall < 0.5) { results.issues.push({ type: 'low_recall', queryId, value: recall, message: Low recall (${(recall * 100).toFixed(1)}%) - missing relevant memories }); } }

results.overallPrecision = totalRetrieved > 0 ? totalRelevantRetrieved / totalRetrieved : 0; results.overallRecall = totalRelevant > 0 ? totalRelevantRetrieved / totalRelevant : 0; results.f1Score = results.overallPrecision + results.overallRecall > 0 ? 2 * (results.overallPrecision * results.overallRecall) / (results.overallPrecision + results.overallRecall) : 0;

return results; }

/**

*/ calculateMRR(queries, groundTruth) { let reciprocalRankSum = 0;

for (const query of queries) { const queryId = query.id || query.text; const relevantIds = groundTruth[queryId] || []; const retrievedIds = query.results?.map(r => r.id) || [];

// Find rank of first relevant result for (let i = 0; i < retrievedIds.length; i++) { if (relevantIds.includes(retrievedIds[i])) { reciprocalRankSum += 1 / (i + 1); break; } } }

return queries.length > 0 ? reciprocalRankSum / queries.length : 0; }

/**

*/ calculateNDCG(queries, groundTruth, relevanceScores, k = 10) { const ndcgScores = [];

for (const query of queries) { const queryId = query.id || query.text; const retrievedIds = query.results?.slice(0, k)?.map(r => r.id) || []; const relevance = relevanceScores[queryId] || {};

// Calculate DCG let dcg = 0; for (let i = 0; i < retrievedIds.length; i++) { const rel = relevance[retrievedIds[i]] || 0; dcg += rel / Math.log2(i + 2); // i+2 because log2(1) = 0 }

// Calculate ideal DCG const idealRelevance = Object.values(relevance).sort((a, b) => b - a).slice(0, k); let idcg = 0; for (let i = 0; i < idealRelevance.length; i++) { idcg += idealRelevance[i] / Math.log2(i + 2); }

const ndcg = idcg > 0 ? dcg / idcg : 0; ndcgScores.push({ queryId, ndcg }); }

return { scores: ndcgScores, average: ndcgScores.reduce((sum, s) => sum + s.ndcg, 0) / ndcgScores.length }; } }

/**

*/ class MultiModalEncodingValidator { constructor() { this.modalities = ['text', 'image', 'audio', 'video', 'structured']; }

/**

*/ validateEncodingConsistency(memories) { const issues = []; const modalityStats = {};

for (const memory of memories) { const modalities = memory.modalities || ['text'];

for (const mod of modalities) { if (!modalityStats[mod]) { modalityStats[mod] = { count: 0, hasEmbedding: 0, hasMetadata: 0 }; }

modalityStats[mod].count++;

if (memory.embeddings?.[mod]) { modalityStats[mod].hasEmbedding++; } else { issues.push({ type: 'missing_embedding', memoryId: memory.id, modality: mod, message: Missing ${mod} embedding for memory ${memory.id} }); }

if (memory.metadata?.[mod]) { modalityStats[mod].hasMetadata++; } } }

// Check for modality imbalance const counts = Object.values(modalityStats).map(s => s.count); const maxCount = Math.max(...counts); const minCount = Math.min(...counts);

if (maxCount > 0 && minCount > 0 && maxCount / minCount > 10) { issues.push({ type: 'modality_imbalance', message: Severe modality imbalance detected: ${JSON.stringify(modalityStats)}, severity: 'warning' }); }

return { modalityStats, issues, consistency: this.calculateConsistencyScore(modalityStats) }; }

/**

*/ calculateConsistencyScore(modalityStats) { const scores = [];

for (const [mod, stats] of Object.entries(modalityStats)) { if (stats.count > 0) { scores.push(stats.hasEmbedding / stats.count); } }

return scores.length > 0 ? scores.reduce((a, b) => a + b, 0) / scores.length : 0; }

/**

*/ checkEmbeddingQuality(memories, modality = 'text') { const issues = []; const stats = { total: 0, dimensions: new Set(), norms: [], sparsity: [] };

for (const memory of memories) { const embedding = memory.embeddings?.[modality]; if (!embedding) continue;

stats.total++; stats.dimensions.add(embedding.length);

// Calculate norm const norm = Math.sqrt(embedding.reduce((sum, v) => sum + v * v, 0)); stats.norms.push(norm);

// Check for zero vectors if (norm === 0) { issues.push({ type: 'zero_embedding', memoryId: memory.id, modality, message: Zero vector embedding for memory ${memory.id} }); }

// Calculate sparsity const zeros = embedding.filter(v => v === 0).length; const sparsity = zeros / embedding.length; stats.sparsity.push(sparsity);

if (sparsity > 0.9) { issues.push({ type: 'sparse_embedding', memoryId: memory.id, modality, value: sparsity, message: Very sparse embedding (${(sparsity * 100).toFixed(1)}% zeros) for memory ${memory.id} }); } }

// Check dimension consistency if (stats.dimensions.size > 1) { issues.push({ type: 'inconsistent_dimensions', dimensions: Array.from(stats.dimensions), message: Inconsistent embedding dimensions: ${Array.from(stats.dimensions).join(', ')} }); }

return { stats: { total: stats.total, dimension: stats.dimensions.size === 1 ? Array.from(stats.dimensions)[0] : null, avgNorm: stats.norms.reduce((a, b) => a + b, 0) / stats.norms.length, avgSparsity: stats.sparsity.reduce((a, b) => a + b, 0) / stats.sparsity.length }, issues }; }

/**

*/ detectCrossModalAlignment(memories) { const issues = []; const alignments = [];

for (const memory of memories) { const modalities = Object.keys(memory.embeddings || {});

if (modalities.length < 2) continue;

// Calculate cross-modal similarity for (let i = 0; i < modalities.length; i++) { for (let j = i + 1; j < modalities.length; j++) { const emb1 = memory.embeddings[modalities[i]]; const emb2 = memory.embeddings[modalities[j]];

if (!emb1 || !emb2) continue;

const similarity = this.cosineSimilarity(emb1, emb2); alignments.push({ memoryId: memory.id, modalities: [modalities[i], modalities[j]], similarity });

// Low cross-modal alignment if (similarity < 0.3) { issues.push({ type: 'low_cross_modal_alignment', memoryId: memory.id, modalities: [modalities[i], modalities[j]], value: similarity, message: Low alignment between ${modalities[i]} and ${modalities[j]} (${similarity.toFixed(3)}) for memory ${memory.id} }); } } } }

return { alignments, issues, avgAlignment: alignments.length > 0 ? alignments.reduce((sum, a) => sum + a.similarity, 0) / alignments.length : 0 }; }

/**

*/ cosineSimilarity(a, b) { if (a.length !== b.length) return 0;

let dotProduct = 0; let normA = 0; let normB = 0;

for (let i = 0; i < a.length; i++) { dotProduct += a[i] * b[i]; normA += a[i] * a[i]; normB += b[i] * b[i]; }

const denom = Math.sqrt(normA) * Math.sqrt(normB); return denom > 0 ? dotProduct / denom : 0; } }

/**

*/ class IndexingEfficiencyChecker { constructor() { this.metrics = {}; }

/**

*/ checkIndexingEfficiency(memories, indexStats) { const issues = [];

// Check index coverage const indexedCount = memories.filter(m => m.indexed).length; const coverage = memories.length > 0 ? indexedCount / memories.length : 0;

if (coverage < 0.95) { issues.push({ type: 'incomplete_indexing', value: coverage, message: Only ${(coverage * 100).toFixed(1)}% of memories are indexed }); }

// Check for stale indices const now = Date.now(); const staleThreshold = 7 * 24 * 60 * 60 * 1000; // 7 days

for (const memory of memories) { if (memory.indexed && memory.indexedAt) { const age = now - new Date(memory.indexedAt).getTime(); if (age > staleThreshold && mem