Commit 876e508a authored by Delvallez Delvallez's avatar Delvallez Delvallez

slides au 22/05 17h15

parent de8c60a9
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
# Latex # Latex
*.aux *.aux
*.fdb_latexmk *.fdb_latexmk
*.html
*.nav *.nav
*.snm *.snm
*.synctex.gz *.synctex.gz
...@@ -10,4 +9,5 @@ ...@@ -10,4 +9,5 @@
*_files/ *_files/
# Quarto # Quarto
*.quarto_ipynb* # .html
\ No newline at end of file # *_files
\ No newline at end of file
<!DOCTYPE html>
<html lang="en"><head>
<script src="slides_files/libs/clipboard/clipboard.min.js"></script>
<script src="slides_files/libs/quarto-html/tabby.min.js"></script>
<script src="slides_files/libs/quarto-html/popper.min.js"></script>
<script src="slides_files/libs/quarto-html/tippy.umd.min.js"></script>
<link href="slides_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="slides_files/libs/quarto-html/light-border.css" rel="stylesheet">
<link href="slides_files/libs/quarto-html/quarto-syntax-highlighting-7f8f88aac4f3542376d5c11b86a4c14d.css" rel="stylesheet" id="quarto-text-highlighting-styles"><meta charset="utf-8">
<meta name="generator" content="quarto-1.9.37">
<meta name="author" content="Marine Delvallez">
<title>Mechanistic interpretability for enhancing RAG models</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="slides_files/libs/revealjs/dist/reset.css">
<link rel="stylesheet" href="slides_files/libs/revealjs/dist/reveal.css">
<style>
/* Default styles provided by pandoc.
** See https://pandoc.org/MANUAL.html#variables-for-html for config info.
*/
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
html { -webkit-text-size-adjust: 100%; }
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ color: #003b4f; background-color: #f1f3f5; }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span { color: #003b4f; } /* Normal */
code span.al { color: #ad0000; } /* Alert */
code span.an { color: #5e5e5e; } /* Annotation */
code span.at { color: #657422; } /* Attribute */
code span.bn { color: #ad0000; } /* BaseN */
code span.bu { } /* BuiltIn */
code span.cf { color: #003b4f; font-weight: bold; } /* ControlFlow */
code span.ch { color: #20794d; } /* Char */
code span.cn { color: #8f5902; } /* Constant */
code span.co { color: #5e5e5e; } /* Comment */
code span.cv { color: #5e5e5e; font-style: italic; } /* CommentVar */
code span.do { color: #5e5e5e; font-style: italic; } /* Documentation */
code span.dt { color: #ad0000; } /* DataType */
code span.dv { color: #ad0000; } /* DecVal */
code span.er { color: #ad0000; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #ad0000; } /* Float */
code span.fu { color: #4758ab; } /* Function */
code span.im { color: #00769e; } /* Import */
code span.in { color: #5e5e5e; } /* Information */
code span.kw { color: #003b4f; font-weight: bold; } /* Keyword */
code span.op { color: #5e5e5e; } /* Operator */
code span.ot { color: #003b4f; } /* Other */
code span.pp { color: #ad0000; } /* Preprocessor */
code span.sc { color: #5e5e5e; } /* SpecialChar */
code span.ss { color: #20794d; } /* SpecialString */
code span.st { color: #20794d; } /* String */
code span.va { color: #111111; } /* Variable */
code span.vs { color: #20794d; } /* VerbatimString */
code span.wa { color: #5e5e5e; font-style: italic; } /* Warning */
/* CSS for citations */
div.csl-bib-body { }
div.csl-entry {
clear: both;
}
.hanging-indent div.csl-entry {
margin-left:2em;
text-indent:-2em;
}
div.csl-left-margin {
min-width:2em;
float:left;
}
div.csl-right-inline {
margin-left:2em;
padding-left:1em;
}
div.csl-indent {
margin-left: 2em;
} </style>
<link rel="stylesheet" href="slides_files/libs/revealjs/dist/theme/quarto-2740581606dc327e82f18f789b69d8a0.css">
<link href="slides_files/libs/revealjs/plugin/quarto-line-highlight/line-highlight.css" rel="stylesheet">
<link href="slides_files/libs/revealjs/plugin/reveal-menu/menu.css" rel="stylesheet">
<link href="slides_files/libs/revealjs/plugin/reveal-menu/quarto-menu.css" rel="stylesheet">
<link href="slides_files/libs/revealjs/plugin/quarto-support/footer.css" rel="stylesheet">
<style type="text/css">
.reveal div.sourceCode {
margin: 0;
overflow: auto;
}
.reveal div.hanging-indent {
margin-left: 1em;
text-indent: -1em;
}
.reveal .slide:not(.center) {
height: 100%;
}
.reveal .slide.scrollable {
overflow-y: auto;
}
.reveal .footnotes {
height: 100%;
overflow-y: auto;
}
.reveal .slide .absolute {
position: absolute;
display: block;
}
.reveal .footnotes ol {
counter-reset: ol;
list-style-type: none;
margin-left: 0;
}
.reveal .footnotes ol li:before {
counter-increment: ol;
content: counter(ol) ". ";
}
.reveal .footnotes ol li > p:first-child {
display: inline-block;
}
.reveal .slide ul,
.reveal .slide ol {
margin-bottom: 0.5em;
}
.reveal .slide ul li,
.reveal .slide ol li {
margin-top: 0.4em;
margin-bottom: 0.2em;
}
.reveal .slide ul[role="tablist"] li {
margin-bottom: 0;
}
.reveal .slide ul li > *:first-child,
.reveal .slide ol li > *:first-child {
margin-block-start: 0;
}
.reveal .slide ul li > *:last-child,
.reveal .slide ol li > *:last-child {
margin-block-end: 0;
}
.reveal .slide .columns:nth-child(3) {
margin-block-start: 0.8em;
}
.reveal blockquote {
box-shadow: none;
}
.reveal .tippy-content>* {
margin-top: 0.2em;
margin-bottom: 0.7em;
}
.reveal .tippy-content>*:last-child {
margin-bottom: 0.2em;
}
.reveal .slide > img.stretch.quarto-figure-center,
.reveal .slide > img.r-stretch.quarto-figure-center {
display: block;
margin-left: auto;
margin-right: auto;
}
.reveal .slide > img.stretch.quarto-figure-left,
.reveal .slide > img.r-stretch.quarto-figure-left {
display: block;
margin-left: 0;
margin-right: auto;
}
.reveal .slide > img.stretch.quarto-figure-right,
.reveal .slide > img.r-stretch.quarto-figure-right {
display: block;
margin-left: auto;
margin-right: 0;
}
</style>
</head>
<body class="quarto-light">
<div class="reveal">
<div class="slides">
<section id="title-slide" class="quarto-title-block center">
<h1 class="title">Mechanistic interpretability for enhancing RAG models</h1>
<div class="quarto-title-authors">
<div class="quarto-title-author">
<div class="quarto-title-author-name">
Marine Delvallez
</div>
</div>
</div>
</section><section id="TOC">
<nav role="doc-toc">
<h2 id="toc-title">Table of contents</h2>
<ul>
<li><a href="#/retrieval-augmented-generation---rag" id="/toc-retrieval-augmented-generation---rag">Retrieval Augmented Generation - RAG</a></li>
<li><a href="#/explainability-in-artificial-intelligence" id="/toc-explainability-in-artificial-intelligence">Explainability in Artificial Intelligence</a></li>
<li><a href="#/presentation-and-demonstration-of-mechir" id="/toc-presentation-and-demonstration-of-mechir">Presentation and Demonstration of MechIR</a></li>
<li><a href="#/demonstration-tasb-vaswani" id="/toc-demonstration-tasb-vaswani">Demonstration (TASB &amp; Vaswani)</a></li>
</ul>
</nav>
</section>
<section>
<section id="retrieval-augmented-generation---rag" class="title-slide slide level2 center">
<h2>Retrieval Augmented Generation - RAG</h2>
</section>
<section id="retrieval-augmented-generation---definition" class="slide level3">
<h3>Retrieval Augmented Generation - Definition</h3>
<div class="quarto-figure quarto-figure-center">
<figure>
<p><img data-src="images/DefRAG.drawio.png"></p>
<figcaption>Simple RAG Architecture <span class="citation" data-cites="lewis_retrieval-augmented_2020">(<a href="#/references" role="doc-biblioref" onclick="">Lewis et al. 2020</a>)</span></figcaption>
</figure>
</div>
<div class="fragment">
<div class="quarto-figure quarto-figure-center">
<figure>
<p><img data-src="images/DefRAGAvance_integration.drawio.png"></p>
<figcaption>Advanced RAG Achitecture <span class="citation" data-cites="fan_survey_2024">(<a href="#/references" role="doc-biblioref" onclick="">Fan et al. 2024</a>)</span></figcaption>
</figure>
</div>
</div>
</section>
<section id="example" class="slide level3 center">
<h3>Example</h3>
<img data-src="images/RAGHN-perso.drawio.png" class="r-stretch quarto-figure-center"><p class="caption">RAG Architecture used here (inspired from <span class="citation" data-cites="tran_retrieval_2024">(<a href="#/references" role="doc-biblioref" onclick="">Tran et al. 2024</a>)</span>)</p></section></section>
<section>
<section id="explainability-in-artificial-intelligence" class="title-slide slide level2 center">
<h2>Explainability in Artificial Intelligence</h2>
</section>
<section id="explainability-in-artificial-intelligence-1" class="slide level3">
<h3>Explainability in Artificial Intelligence</h3>
<p><em>Open black box models</em></p>
<h4 id="aims">Aims</h4>
<ul>
<li>Trustability</li>
<li>Understandability</li>
<li>Model Rectification</li>
</ul>
</section>
<section id="definitions" class="slide level3">
<h3>Definitions</h3>
<p><strong>XAI</strong> : Make model’s behavior understandable for human <span class="citation" data-cites="bell_its_2022">(<a href="#/references" role="doc-biblioref" onclick="">Bell et al. 2022</a>)</span><br>
<strong>Understand</strong> : Predict model’s behavior <span class="citation" data-cites="bell_its_2022">(<a href="#/references" role="doc-biblioref" onclick="">Bell et al. 2022</a>)</span><br>
<strong>Explanation</strong> : Any way to make the decision process of the model understandable for human</p>
<div class="columns">
<div class="column" style="width:40%;">
<p><strong>Interpretability</strong><br>
<em>How ?</em></p>
</div><div class="column" style="width:40%;">
<p><strong>Explanability</strong><br>
<em>Why ?</em></p>
</div></div>
</section>
<section id="explanation-through-creation-of-a-model" class="slide level3">
<h3>Explanation through creation of a model</h3>
<img data-src="images/VieModele-TempsXAI.drawio.png" class="r-stretch quarto-figure-center"><p class="caption">Explanation through creation of a model</p></section></section>
<section>
<section id="presentation-and-demonstration-of-mechir" class="title-slide slide level2 center">
<h2>Presentation and Demonstration of MechIR</h2>
</section>
<section id="mechir" class="slide level3">
<h3>MechIR</h3>
<h4 id="mechanistic-interpretability">Mechanistic interpretability</h4>
<p>Understand the internal mechanisms of neural networks by <strong>performing causal interventions</strong> on specific model components</p>
<h4 id="mechir-parry_mechir_2025">MechIR <span class="citation" data-cites="parry_mechir_2025">(<a href="#/references" role="doc-biblioref" onclick="">Parry et al. 2025</a>)</span></h4>
<ul>
<li><p>Encoder-only models</p></li>
<li><p>For Information Retrieval models</p></li>
<li><p>Identify components responsible for some behavior</p></li>
<li><p>Activation Patching Technique</p></li>
</ul>
</section>
<section id="activation-patching-chen_axiomatic_2024" class="slide level3 smaller">
<h3>Activation Patching <span class="citation" data-cites="chen_axiomatic_2024">(<a href="#/references" role="doc-biblioref" onclick="">Chen et al. 2024</a>)</span></h3>
<p>Let <span class="math inline">\(Q \times D \subset \mathcal{Q}\times\mathcal{D}\)</span> be a set of pairs of questions and documents<br>
Let <span class="math inline">\(Q \times \tilde{D}\)</span> the same set of pairs but with perturbed documents</p>
<ol type="1">
<li class="fragment">Forward pass all <span class="math inline">\(Q\times D\)</span>
<ul>
<li class="fragment">record <span class="math inline">\(o_{i,j}^e\)</span> the output of each component <span class="math inline">\(n_{i,j}, \forall e \in Q\times D\)</span></li>
<li class="fragment">record <span class="math inline">\(p_D\)</span> the performance of the model</li>
</ul></li>
<li class="fragment">Forward pass all <span class="math inline">\(Q\times \tilde{D}\)</span>
<ul>
<li class="fragment">record <span class="math inline">\(o_{i,j}^\tilde{e}\)</span> the output of each component <span class="math inline">\(n_{i,j}, \forall \tilde{e} \in Q\times \tilde{D}\)</span></li>
<li class="fragment">record <span class="math inline">\(p_\tilde{D}\)</span> the performance of the model<br>
</li>
</ul></li>
<li class="fragment">Rewrite <span class="math inline">\(D, e, \tilde{D} \text{ and } \tilde{e}\)</span> as
<ul>
<li class="fragment"><span class="math inline">\(\hat{D}, \hat{e}, \check{D} \text{ and } \check{e}\)</span> if <span class="math inline">\(p_D &gt; p_\tilde{D}\)</span></li>
<li class="fragment"><span class="math inline">\(\check{D}, \check{e}, \hat{D} \text{ and } \hat{e}\)</span> otherwise</li>
</ul></li>
</ol>
</section>
<section id="activation-patching-chen_axiomatic_2024-1" class="slide level3 smaller">
<h3>Activation Patching <span class="citation" data-cites="chen_axiomatic_2024">(<a href="#/references" role="doc-biblioref" onclick="">Chen et al. 2024</a>)</span></h3>
<ol start="3" type="1">
<li>Rewrite <span class="math inline">\(D, e, \tilde{D} \text{ and } \tilde{e}\)</span> as
<ul>
<li><span class="math inline">\(\hat{D}, \hat{e}, \check{D} \text{ and } \check{e}\)</span> if <span class="math inline">\(p_D &gt; p_\tilde{D}\)</span></li>
<li><span class="math inline">\(\check{D}, \check{e}, \hat{D} \text{ and } \hat{e}\)</span> otherwise</li>
</ul></li>
</ol>
<ol start="4" type="1">
<li class="fragment">For each component <span class="math inline">\(n_{i,j}\)</span> forward pass <span class="math inline">\(Q\times\check{D}\)</span> but replace <span class="math inline">\(o_{i,j}^{\check{e}}\)</span> by <span class="math inline">\(o_{i,j}^{\hat{e}}\)</span> for each <span class="math inline">\(\check{e}\)</span>. Record the performance <span class="math inline">\(\bar{p}\)</span></li>
<li class="fragment"><span class="math inline">\(P = \frac{\bar{p} - p_\hat{D} }{p_\check{D} - p_\hat{D}}\)</span> gives the impact of the perturbation on the model performance</li>
</ol>
</section>
<section id="animation-de-lexecution-de-activation-patching" class="slide level3">
<h3>Animation de l’execution de Activation patching</h3>
</section>
<section id="step-1-choose-a-perturbation" class="slide level3">
<h3>Step 1: Choose a perturbation</h3>
<p>Function that applies the same modification on each document.<br>
Example :</p>
<div id="fb3865be" class="cell" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1"><pre class="sourceCode numberSource python number-lines code-with-copy"><code class="sourceCode python"><span id="cb1-1"><a href=""></a><span class="at">@perturbation</span></span>
<span id="cb1-2"><a href=""></a><span class="kw">def</span> pert1(doc:<span class="bu">str</span>) <span class="op">-&gt;</span> <span class="bu">str</span> :</span>
<span id="cb1-3"><a href=""></a> <span class="cf">return</span> doc.replace(<span class="st">"solution"</span>, <span class="st">"answer"</span>)</span>
<span id="cb1-4"><a href=""></a></span>
<span id="cb1-5"><a href=""></a><span class="at">@perturbation</span></span>
<span id="cb1-6"><a href=""></a><span class="kw">def</span> pert2(doc:<span class="bu">str</span>) <span class="op">-&gt;</span> <span class="bu">str</span>:</span>
<span id="cb1-7"><a href=""></a> <span class="cf">return</span> doc.replace(<span class="st">"microwave"</span>, <span class="st">"toaster"</span>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</div>
<h4 id="perturbation-creation-technique">Perturbation creation technique</h4>
<ul>
<li>Identify vocabulary specific to the dataset</li>
<li>Find in the vocabulary words with several meaning <span class="math inline">\(m_D\)</span> and <span class="math inline">\(m_D\)</span></li>
<li>Replace that word by a synonym of the <span class="math inline">\(m_D\)</span> meaning</li>
</ul>
</section>
<section id="what-is-a-good-perturbation" class="slide level3">
<h3>What is a good perturbation</h3>
<ul>
<li>Has an impact of the documents representation</li>
<li>Be useful for interpretation</li>
</ul>
<img data-src="images/perturbation-score.png" class="r-stretch quarto-figure-center"><p class="caption">Perturbation Score</p></section>
<section id="step-2-instantiate-the-model-and-load-data" class="slide level3">
<h3>Step 2 : Instantiate the model and load data</h3>
<div id="fb2237a1" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2"><pre class="sourceCode numberSource python number-lines code-with-copy"><code class="sourceCode python"><span id="cb2-1"><a href=""></a>dot_model_name <span class="op">=</span> <span class="st">"sebastian-hofstaetter/distilbert-dot-tas_b-b256-msmarco"</span></span>
<span id="cb2-2"><a href=""></a>dot_model <span class="op">=</span> Dot(dot_model_name)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<pre><code>Moving model to device: cpu
Loaded pretrained model sebastian-hofstaetter/distilbert-dot-tas_b-b256-msmarco into HookedEncoder</code></pre>
</div>
</div>
<div id="643e5775" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4"><pre class="sourceCode numberSource python number-lines code-with-copy"><code class="sourceCode python"><span id="cb4-1"><a href=""></a>dataset <span class="op">=</span> MechIRDataset(<span class="st">"vaswani"</span>, query_id_subset<span class="op">=</span>[<span class="st">"1"</span>])</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</div>
<div id="45b5abab" class="cell" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5"><pre class="sourceCode numberSource python number-lines code-with-copy"><code class="sourceCode python"><span id="cb5-1"><a href=""></a>pert1_dot_collator <span class="op">=</span> DotDataCollator(dot_model.tokenizer, pert1, q_max_length<span class="op">=</span><span class="va">None</span>, d_max_length<span class="op">=</span><span class="va">None</span>, perturb_type<span class="op">=</span><span class="st">"replace"</span>)</span>
<span id="cb5-2"><a href=""></a>pert1_dot_dataloader <span class="op">=</span> DataLoader(dataset, batch_size<span class="op">=</span><span class="dv">16</span>, collate_fn<span class="op">=</span>pert1_dot_collator)</span>
<span id="cb5-3"><a href=""></a></span>
<span id="cb5-4"><a href=""></a>pert2_dot_collator <span class="op">=</span> DotDataCollator(dot_model.tokenizer, pert2, q_max_length<span class="op">=</span><span class="va">None</span>, d_max_length<span class="op">=</span><span class="va">None</span>, perturb_type<span class="op">=</span><span class="st">"replace"</span>)</span>
<span id="cb5-5"><a href=""></a>pert2_dot_dataloader <span class="op">=</span> DataLoader(dataset, batch_size<span class="op">=</span><span class="dv">16</span>, collate_fn<span class="op">=</span>pert2_dot_collator)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</div>
</section>
<section id="visualisation-of-perturbed-data" class="slide level3">
<h3>Visualisation of perturbed data</h3>
<div id="af41b638" class="cell" data-execution_count="6">
<div class="cell-output cell-output-stdout">
<pre><code>solution -&gt; answer
Query: [CLS] measurement of dielectric constant of liquids by the use of microwave techniques [SEP]
Baseline Document: [CLS] broadband millimetre wave paramagnetic resonance spectrometer the specimen and waveguide which can be cooled by means of a cryostat are placed between close pole pieces giving high uniform magnetic fields design details and some measurements on zero field splittings are given [SEP]
Perturbed Document: [CLS] broadband millimetre wave paramagnetic resonance spectrometer the specimen and waveguide which can be cooled by means of a cryostat are placed between close pole pieces giving high uniform magnetic fields design details and some measurements on zero field splittings are given [SEP]
==================================================
Query: [CLS] measurement of dielectric constant of liquids by the use of microwave techniques [SEP]
Baseline Document: [CLS] microwave measurements of dielectric absorption in dilute solutions [SEP]
Perturbed Document: [CLS] microwave measurements of dielectric absorption in dilute answers [SEP]
==================================================</code></pre>
</div>
</div>
<div id="b8e9a036" class="cell" data-execution_count="7">
<div class="cell-output cell-output-stdout">
<pre><code>microwave -&gt; toaster
Query: [CLS] measurement of dielectric constant of liquids by the use of microwave techniques [SEP]
Baseline Document: [CLS] broadband millimetre wave paramagnetic resonance spectrometer the specimen and waveguide which can be cooled by means of a cryostat are placed between close pole pieces giving high uniform magnetic fields design details and some measurements on zero field splittings are given [SEP]
Perturbed Document: [CLS] broadband millimetre wave paramagnetic resonance spectrometer the specimen and waveguide which can be cooled by means of a cryostat are placed between close pole pieces giving high uniform magnetic fields design details and some measurements on zero field splittings are given [SEP]
==================================================
Query: [CLS] measurement of dielectric constant of liquids by the use of microwave techniques [SEP]
Baseline Document: [CLS] microwave a measurements of dielectric absorption in dilute solutions [SEP]
Perturbed Document: [CLS] toaster measurements of dielectric absorption in dilute solutions [SEP]
==================================================</code></pre>
</div>
</div>
</section>
<section id="step-4-measure-the-impact-of-the-perturbation-on-the-model" class="slide level3">
<h3>Step 4 : Measure the impact of the perturbation on the model</h3>
<div id="0fce16c2" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8"><pre class="sourceCode numberSource python number-lines code-with-copy"><code class="sourceCode python"><span id="cb8-1"><a href=""></a><span class="co"># Initialize lists to store baseline and perturbed performances for each dataloader</span></span>
<span id="cb8-2"><a href=""></a>all_baseline_performance <span class="op">=</span> {<span class="st">"pert1"</span>: [], <span class="st">"pert2"</span>: []}</span>
<span id="cb8-3"><a href=""></a>all_perturbed_performance <span class="op">=</span> {<span class="st">"pert1"</span>: [], <span class="st">"pert2"</span>: []}</span>
<span id="cb8-4"><a href=""></a></span>
<span id="cb8-5"><a href=""></a><span class="co"># Calculate performances for each perturbation_type</span></span>
<span id="cb8-6"><a href=""></a>calculate_performance(dot_model, pert1_dot_dataloader, all_baseline_performance[<span class="st">"pert1"</span>], all_perturbed_performance[<span class="st">"pert1"</span>])</span>
<span id="cb8-7"><a href=""></a>calculate_performance(dot_model, pert2_dot_dataloader, all_baseline_performance[<span class="st">"pert2"</span>], all_perturbed_performance[<span class="st">"pert2"</span>])</span>
<span id="cb8-8"><a href=""></a></span>
<span id="cb8-9"><a href=""></a>plot_score_dists_mult(all_baseline_performance, all_perturbed_performance, plot_type<span class="op">=</span><span class="st">"kde"</span>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display">
<div>
<figure>
<p><img data-src="slides_files/figure-revealjs/cell-9-output-1.png" width="1430" height="381"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="step-5-chart-the-sensitivity-of-the-model-to-the-perturbation" class="slide level3">
<h3>Step 5 : Chart the sensitivity of the model to the perturbation</h3>
<div id="d2046f7e" class="cell" data-execution_count="9">
<div class="cell-output cell-output-display">
<div>
<figure>
<p><img data-src="slides_files/figure-revealjs/cell-10-output-1.png" width="765" height="523"></p>
</figure>
</div>
</div>
</div>
<!-- ![Chart of the impact of a perturbation on the components](images/ActivationPatchingAllHeadExempleMechIR.png) -->
</section>
<section id="perspective-enhance-a-model-with-mechir" class="slide level3">
<h3>Perspective : Enhance a model with MechIR</h3>
<p>TODO</p>
</section>
<section id="references" class="slide level3 smaller scrollable">
<h3>References</h3>
<div id="refs" class="references csl-bib-body hanging-indent" role="list">
<div id="ref-bell_its_2022" class="csl-entry" role="listitem">
Bell, Andrew, Ian Solano-Kamaiko, Oded Nov, and Julia Stoyanovich. 2022. <span>“It’s <span>Just</span> <span>Not</span> <span>That</span> <span>Simple</span>: <span>An</span> <span>Empirical</span> <span>Study</span> of the <span>Accuracy</span>-<span>Explainability</span> <span>Trade</span>-Off in <span>Machine</span> <span>Learning</span> for <span>Public</span> <span>Policy</span>.”</span> <em>2022 <span>ACM</span> <span>Conference</span> on <span>Fairness</span> <span>Accountability</span> and <span>Transparency</span></em> (Seoul Republic of Korea), June, 248–66. <a href="https://doi.org/10.1145/3531146.3533090">https://doi.org/10.1145/3531146.3533090</a>.
</div>
<div id="ref-chen_axiomatic_2024" class="csl-entry" role="listitem">
Chen, Catherine, Jack Merullo, and Carsten Eickhoff. 2024. <span>“Axiomatic <span>Causal</span> <span>Interventions</span> for <span>Reverse</span> <span>Engineering</span> <span>Relevance</span> <span>Computation</span> in <span>Neural</span> <span>Retrieval</span> <span>Models</span>.”</span> <em>Proceedings of the 47th <span>International</span> <span>ACM</span> <span>SIGIR</span> <span>Conference</span> on <span>Research</span> and <span>Development</span> in <span>Information</span> <span>Retrieval</span></em> (Washington DC USA), July, 1401–10. <a href="https://doi.org/10.1145/3626772.3657841">https://doi.org/10.1145/3626772.3657841</a>.
</div>
<div id="ref-fan_survey_2024" class="csl-entry" role="listitem">
Fan, Wenqi, Yujuan Ding, Liangbo Ning, et al. 2024. <em>A <span>Survey</span> on <span>RAG</span> <span>Meeting</span> <span>LLMs</span>: <span>Towards</span> <span>Retrieval</span>-<span>Augmented</span> <span>Large</span> <span>Language</span> <span>Models</span></em>. arXiv. <a href="https://doi.org/10.48550/arXiv.2405.06211">https://doi.org/10.48550/arXiv.2405.06211</a>.
</div>
<div id="ref-lewis_retrieval-augmented_2020" class="csl-entry" role="listitem">
Lewis, Patrick, Ethan Perez, Aleksandra Piktus, et al. 2020. <span>“Retrieval-<span>Augmented</span> <span>Generation</span> for <span>Knowledge</span>-<span>Intensive</span> <span>NLP</span> <span>Tasks</span>.”</span> <em>arXiv: Computation and Language</em>.
</div>
<div id="ref-parry_mechir_2025" class="csl-entry" role="listitem">
Parry, Andrew, Catherine Chen, Carsten Eickhoff, and Sean MacAvaney. 2025. <span><span>MechIR</span>: <span>A</span> <span>Mechanistic</span> <span>Interpretability</span> <span>Framework</span> for <span>Information</span> <span>Retrieval</span>.”</span> <em>Advances in <span>Information</span> <span>Retrieval</span> - 47th <span>European</span> <span>Conference</span> on <span>Information</span> <span>Retrieval</span>, <span>ECIR</span> 2025, <span>Lucca</span>, <span>Italy</span>, <span>April</span> 6-10, 2025, <span>Proceedings</span>, <span>Part</span> <span>V</span></em>, Lecture <span>Notes</span> in <span>Computer</span> <span>Science</span>, vol. 15576: 89–95. <a href="https://doi.org/10.1007/978-3-031-88720-8_16">https://doi.org/10.1007/978-3-031-88720-8_16</a>.
</div>
<div id="ref-tran_retrieval_2024" class="csl-entry" role="listitem">
Tran, The Trung, Carlos-Emiliano González-Gallardo, and Antoine Doucet. 2024. <span>“Retrieval <span>Augmented</span> <span>Generation</span> for <span>Historical</span> <span>Newspapers</span>.”</span> <em>Proceedings of the 24th <span>ACM</span>/<span>IEEE</span> <span>Joint</span> <span>Conference</span> on <span>Digital</span> <span>Libraries</span></em> (Hong Kong China), December, 1–5. <a href="https://doi.org/10.1145/3677389.3702542">https://doi.org/10.1145/3677389.3702542</a>.
</div>
</div>
</section></section>
<section id="demonstration-tasb-vaswani" class="title-slide slide level2 center">
<h2>Demonstration (TASB &amp; Vaswani)</h2>
</section>
</div>
<div class="quarto-auto-generated-content" style="display: none;">
<div class="footer footer-default">
</div>
</div></div>
<script>window.backupDefine = window.define; window.define = undefined;</script>
<script src="slides_files/libs/revealjs/dist/reveal.js"></script>
<!-- reveal.js plugins -->
<script src="slides_files/libs/revealjs/plugin/quarto-line-highlight/line-highlight.js"></script>
<script src="slides_files/libs/revealjs/plugin/pdf-export/pdfexport.js"></script>
<script src="slides_files/libs/revealjs/plugin/reveal-menu/menu.js"></script>
<script src="slides_files/libs/revealjs/plugin/reveal-menu/quarto-menu.js"></script>
<script src="slides_files/libs/revealjs/plugin/quarto-support/support.js"></script>
<script src="slides_files/libs/revealjs/plugin/notes/notes.js"></script>
<script src="slides_files/libs/revealjs/plugin/search/search.js"></script>
<script src="slides_files/libs/revealjs/plugin/zoom/zoom.js"></script>
<script src="slides_files/libs/revealjs/plugin/math/math.js"></script>
<script>window.define = window.backupDefine; window.backupDefine = undefined;</script>
<script>
// Full list of configuration options available at:
// https://revealjs.com/config/
Reveal.initialize({
'controlsAuto': true,
'previewLinksAuto': false,
'pdfSeparateFragments': false,
'autoAnimateEasing': "ease",
'autoAnimateDuration': 1,
'autoAnimateUnmatched': true,
'jumpToSlide': true,
'menu': {"side":"left","useTextContentForMissingTitles":true,"markers":false,"loadIcons":false,"custom":[{"title":"Tools","icon":"<i class=\"fas fa-gear\"></i>","content":"<ul class=\"slide-menu-items\">\n<li class=\"slide-tool-item active\" data-item=\"0\"><a href=\"#\" onclick=\"RevealMenuToolHandlers.fullscreen(event)\"><kbd>f</kbd> Fullscreen</a></li>\n<li class=\"slide-tool-item\" data-item=\"1\"><a href=\"#\" onclick=\"RevealMenuToolHandlers.speakerMode(event)\"><kbd>s</kbd> Speaker View</a></li>\n<li class=\"slide-tool-item\" data-item=\"2\"><a href=\"#\" onclick=\"RevealMenuToolHandlers.overview(event)\"><kbd>o</kbd> Slide Overview</a></li>\n<li class=\"slide-tool-item\" data-item=\"3\"><a href=\"#\" onclick=\"RevealMenuToolHandlers.togglePdfExport(event)\"><kbd>e</kbd> PDF Export Mode</a></li>\n<li class=\"slide-tool-item\" data-item=\"4\"><a href=\"#\" onclick=\"RevealMenuToolHandlers.toggleScrollView(event)\"><kbd>r</kbd> Scroll View Mode</a></li>\n<li class=\"slide-tool-item\" data-item=\"5\"><a href=\"#\" onclick=\"RevealMenuToolHandlers.keyboardHelp(event)\"><kbd>?</kbd> Keyboard Help</a></li>\n</ul>"}],"openButton":true},
'smaller': false,
// Display controls in the bottom right corner
controls: false,
// Help the user learn the controls by providing hints, for example by
// bouncing the down arrow when they first encounter a vertical slide
controlsTutorial: false,
// Determines where controls appear, "edges" or "bottom-right"
controlsLayout: 'edges',
// Visibility rule for backwards navigation arrows; "faded", "hidden"
// or "visible"
controlsBackArrows: 'faded',
// Display a presentation progress bar
progress: true,
// Display the page number of the current slide
slideNumber: false,
// 'all', 'print', or 'speaker'
showSlideNumber: 'all',
// Add the current slide number to the URL hash so that reloading the
// page/copying the URL will return you to the same slide
hash: true,
// Start with 1 for the hash rather than 0
hashOneBasedIndex: false,
// Flags if we should monitor the hash and change slides accordingly
respondToHashChanges: true,
// Push each slide change to the browser history
history: true,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Enable the slide overview mode
overview: true,
// Disables the default reveal.js slide layout (scaling and centering)
// so that you can use custom CSS layout
disableLayout: false,
// Vertical centering of slides
center: false,
// Enables touch navigation on devices with touch input
touch: true,
// Loop the presentation
loop: false,
// Change the presentation direction to be RTL
rtl: false,
// see https://revealjs.com/vertical-slides/#navigation-mode
navigationMode: 'linear',
// Randomizes the order of slides each time the presentation loads
shuffle: false,
// Turns fragments on and off globally
fragments: true,
// Flags whether to include the current fragment in the URL,
// so that reloading brings you to the same fragment position
fragmentInURL: false,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
// Flags if we should show a help overlay when the questionmark
// key is pressed
help: true,
// Flags if it should be possible to pause the presentation (blackout)
pause: true,
// Flags if speaker notes should be visible to all viewers
showNotes: false,
// Global override for autoplaying embedded media (null/true/false)
autoPlayMedia: null,
// Global override for preloading lazy-loaded iframes (null/true/false)
preloadIframes: null,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
// Use this method for navigation when auto-sliding
autoSlideMethod: null,
// Specify the average time in seconds that you think you will spend
// presenting each slide. This is used to show a pacing timer in the
// speaker view
defaultTiming: null,
// Enable slide navigation via mouse wheel
mouseWheel: true,
// The display mode that will be used to show slides
display: 'block',
// Hide cursor if inactive
hideInactiveCursor: true,
// Time before the cursor is hidden (in ms)
hideCursorTime: 5000,
// Opens links in an iframe preview overlay
previewLinks: false,
// Transition style (none/fade/slide/convex/concave/zoom)
transition: 'none',
// Transition speed (default/fast/slow)
transitionSpeed: 'default',
// Transition style for full page slide backgrounds
// (none/fade/slide/convex/concave/zoom)
backgroundTransition: 'none',
// Number of slides away from the current that are visible
viewDistance: 3,
// Number of slides away from the current that are visible on mobile
// devices. It is advisable to set this to a lower number than
// viewDistance in order to save resources.
mobileViewDistance: 2,
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions. Can be
// specified using percentage units.
width: 1050,
height: 700,
// Factor of the display size that should remain empty around the content
margin: 0.1,
math: {
mathjax: 'https://cdn.jsdelivr.net/npm/mathjax@2.7.9/MathJax.js',
config: 'TeX-AMS_HTML-full',
tex2jax: {
inlineMath: [['\\(','\\)']],
displayMath: [['\\[','\\]']],
balanceBraces: true,
processEscapes: false,
processRefs: true,
processEnvironments: true,
preview: 'TeX',
skipTags: ['script','noscript','style','textarea','pre','code'],
ignoreClass: 'tex2jax_ignore',
processClass: 'tex2jax_process'
},
},
// reveal.js plugins
plugins: [QuartoLineHighlight, PdfExport, RevealMenu, QuartoSupport,
RevealMath,
RevealNotes,
RevealSearch,
RevealZoom
]
});
</script>
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const tabsets = window.document.querySelectorAll(".panel-tabset-tabby")
tabsets.forEach(function(tabset) {
const tabby = new Tabby('#' + tabset.id);
});
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const onCopySuccess = function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
}
const getTextToCopy = function(trigger) {
const outerScaffold = trigger.parentElement.cloneNode(true);
const codeEl = outerScaffold.querySelector('code');
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', {
text: getTextToCopy
});
clipboard.on('success', onCopySuccess);
if (window.document.getElementById('quarto-embedded-source-code-modal')) {
const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', {
text: getTextToCopy,
container: window.document.getElementById('quarto-embedded-source-code-modal')
});
clipboardModal.on('success', onCopySuccess);
}
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.closest('section.slide') || el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'light-border',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
config['offset'] = [0,0];
config['maxWidth'] = 700;
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const findCites = (el) => {
const parentEl = el.parentElement;
if (parentEl) {
const cites = parentEl.dataset.cites;
if (cites) {
return {
el,
cites: cites.split(' ')
};
} else {
return findCites(el.parentElement)
}
} else {
return undefined;
}
};
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const citeInfo = findCites(ref);
if (citeInfo) {
tippyHover(citeInfo.el, function() {
var popup = window.document.createElement('div');
citeInfo.cites.forEach(function(cite) {
var citeDiv = window.document.createElement('div');
citeDiv.classList.add('hanging-indent');
citeDiv.classList.add('csl-entry');
var biblioDiv = window.document.getElementById('ref-' + cite);
if (biblioDiv) {
citeDiv.innerHTML = biblioDiv.innerHTML;
}
popup.appendChild(citeDiv);
});
return popup.innerHTML;
});
}
}
});
</script>
</body></html>
\ No newline at end of file
...@@ -7,7 +7,10 @@ format: ...@@ -7,7 +7,10 @@ format:
toc-depth: 2 toc-depth: 2
slide-level: 3 slide-level: 3
mouse-wheel: true mouse-wheel: true
jupyter : python3 jupyter: venv-mechir
# execute:
# cache: true
# freeze: auto
bibliography: biblio.bib bibliography: biblio.bib
style: | style: |
.columns { .columns {
...@@ -75,10 +78,117 @@ _Why ?_ ...@@ -75,10 +78,117 @@ _Why ?_
![Explanation through creation of a model](images/VieModele-TempsXAI.drawio.png) ![Explanation through creation of a model](images/VieModele-TempsXAI.drawio.png)
## Presentation of MechIR ## Presentation and Demonstration of MechIR
### MechIR ### MechIR
```{python}
from mechir import Dot
from mechir.data import MechIRDataset, DotDataCollator
from mechir.perturb import perturbation
from mechir.plotting import plot_components
import torch
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import seaborn as sns
# Helper function to print query/baseline document/perturbed document triplets
def pretty_print_triplets(batch, tokenizer, num=1):
"""
Pretty prints triplets of queries, documents, and their corresponding perturbed documents from a batch.
Args:
batch (dict): A dictionary containing 'queries', 'documents', and 'perturbed_documents' from a DataLoader.
tokenizer: The tokenizer used to decode the input IDs.
num (int): Number of examples to show per batch.
"""
# Get the queries, documents, and perturbed documents from the batch
queries = batch["queries"]
documents = batch["documents"]
perturbed_documents = batch["perturbed_documents"]
# Loop through number of examples to show in batch
for i in range(len(documents["input_ids"][:num])):
# Get the input IDs
query_ids = queries["input_ids"][i]
original_ids = documents["input_ids"][i]
perturbed_ids = perturbed_documents["input_ids"][i]
# Decode the input IDs to text
query_decoded = tokenizer.decode(query_ids.tolist(), skip_special_tokens=False).replace("[PAD]", "").strip()
original_doc_decoded = tokenizer.decode(original_ids.tolist(), skip_special_tokens=False).replace("[PAD]", "").strip()
perturbed_doc_decoded = tokenizer.decode(perturbed_ids.tolist(), skip_special_tokens=False).replace("[PAD]", "").strip()
# Pretty print
# print(f"Triplet {i + 1}:")
print("Query:", query_decoded)
print("Baseline Document:", original_doc_decoded)
print("Perturbed Document:", perturbed_doc_decoded)
print("=" * 50) # Separator for clarity
# Helper function to calculate and store performances
def calculate_performance(model, dataloader, baseline_performance, perturbed_performance):
for i, batch in enumerate(dataloader):
# Get the queries, documents, and perturbed documents from the batch
queries = batch["queries"]
documents = batch["documents"]
perturbed_documents = batch["perturbed_documents"]
# Encode queries, baseline, and perturbed documents
queries_encoded = model.forward(**queries) # [batch_size x hidden_dim]
baseline_encoded = model.forward(**documents) # [batch_size x hidden_dim]
perturbed_encoded = model.forward(**perturbed_documents) # [batch_size x hidden_dim]
# Calculate scores
baseline_scores = torch.sum(queries_encoded.unsqueeze(1) * baseline_encoded.unsqueeze(0), dim=2)
perturbed_scores = torch.sum(queries_encoded.unsqueeze(1) * perturbed_encoded.unsqueeze(0), dim=2)
# Append flattened scores to the performance lists
baseline_performance += baseline_scores.flatten().tolist()
perturbed_performance += perturbed_scores.flatten().tolist()
# Helper function to plot score distributions between baseline and perturbed documents
def plot_score_dists_mult(all_baseline_scores, all_perturbed_scores, plot_type="hist"):
# Number of subplots (one per perturbation type)
num_plots = len(all_baseline_scores)
# Set up the figure to hold multiple subplots in a single row
fig, axs = plt.subplots(1, num_plots, figsize=(15, 4), sharey=True)
fig.suptitle('Distribution of Baseline vs Perturbed Scores', fontsize=16)
for idx, (perturb_type, ax) in enumerate(zip(all_baseline_scores.keys(), axs)):
baseline_scores = all_baseline_scores[perturb_type]
perturbed_scores = all_perturbed_scores[perturb_type]
if plot_type == "hist":
ax.hist(baseline_scores, label='Baseline', color='blue', alpha=0.5, bins=15)
ax.hist(perturbed_scores, label='Perturbed', color='orange', alpha=0.5, bins=15)
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_ylabel('Frequency')
ax.legend()
elif plot_type == "kde":
# Use seaborn for KDE plot, smoother distribution representation
sns.kdeplot(baseline_scores, label='Baseline', color='#D55E00', fill=True, ax=ax, alpha=0.5)
sns.kdeplot(perturbed_scores, label='Perturbed', color='#009E73', fill=True, ax=ax, alpha=0.5)
ax.set_ylabel('Density')
ax.legend()
elif plot_type == "box":
ax.boxplot([baseline_scores, perturbed_scores], tick_labels=['Baseline', 'Perturbed'])
ax.set_ylabel('Scores')
ax.set_xlabel('Scores')
ax.set_title(f'{perturb_type.capitalize()}')
plt.tight_layout(rect=[0, 0, 1, 0.95]) # Adjust layout to make space for the title
plt.show()
return
```
#### Mechanistic interpretability #### Mechanistic interpretability
Understand the internal mechanisms of neural networks by **performing causal interventions** on specific model components Understand the internal mechanisms of neural networks by **performing causal interventions** on specific model components
...@@ -109,11 +219,13 @@ Let $Q \times \tilde{D}$ the same set of pairs but with perturbed documents ...@@ -109,11 +219,13 @@ Let $Q \times \tilde{D}$ the same set of pairs but with perturbed documents
### Activation Patching [@chen_axiomatic_2024] {.smaller} ### Activation Patching [@chen_axiomatic_2024] {.smaller}
:::{.incremental}
3. Rewrite $D, e, \tilde{D} \text{ and } \tilde{e}$ as 3. Rewrite $D, e, \tilde{D} \text{ and } \tilde{e}$ as
- $\hat{D}, \hat{e}, \check{D} \text{ and } \check{e}$ if $p_D > p_\tilde{D}$ - $\hat{D}, \hat{e}, \check{D} \text{ and } \check{e}$ if $p_D > p_\tilde{D}$
- $\check{D}, \check{e}, \hat{D} \text{ and } \hat{e}$ otherwise - $\check{D}, \check{e}, \hat{D} \text{ and } \hat{e}$ otherwise
:::{.incremental}
4. For each component $n_{i,j}$ forward pass $Q\times\check{D}$ but replace $o_{i,j}^{\check{e}}$ by $o_{i,j}^{\hat{e}}$ for each $\check{e}$. Record the performance $\bar{p}$ 4. For each component $n_{i,j}$ forward pass $Q\times\check{D}$ but replace $o_{i,j}^{\check{e}}$ by $o_{i,j}^{\hat{e}}$ for each $\check{e}$. Record the performance $\bar{p}$
5. $P = \frac{\bar{p} - p_\hat{D} }{p_\check{D} - p_\hat{D}}$ gives the impact of the perturbation on the model performance 5. $P = \frac{\bar{p} - p_\hat{D} }{p_\check{D} - p_\hat{D}}$ gives the impact of the perturbation on the model performance
...@@ -121,14 +233,22 @@ Let $Q \times \tilde{D}$ the same set of pairs but with perturbed documents ...@@ -121,14 +233,22 @@ Let $Q \times \tilde{D}$ the same set of pairs but with perturbed documents
### Animation de l'execution de Activation patching ### Animation de l'execution de Activation patching
### Perturbation
### Step 1: Choose a perturbation
Function that applies the same modification on each document. Function that applies the same modification on each document.
Example : Example :
``` {python} ``` {python}
#| echo: true #| echo: true
def perturbation(doc):
@perturbation
def pert1(doc:str) -> str :
return doc.replace("solution", "answer")
@perturbation
def pert2(doc:str) -> str:
return doc.replace("microwave", "toaster") return doc.replace("microwave", "toaster")
``` ```
...@@ -146,14 +266,90 @@ def perturbation(doc): ...@@ -146,14 +266,90 @@ def perturbation(doc):
![Perturbation Score](images/perturbation-score.png) ![Perturbation Score](images/perturbation-score.png)
### Chart Information Retrieval Model ### Step 2 : Instantiate the model and load data
```{python}
#| echo: true
dot_model_name = "sebastian-hofstaetter/distilbert-dot-tas_b-b256-msmarco"
dot_model = Dot(dot_model_name)
```
```{python}
#| echo: true
dataset = MechIRDataset("vaswani", query_id_subset=["1"])
```
```{python}
#| echo: true
pert1_dot_collator = DotDataCollator(dot_model.tokenizer, pert1, q_max_length=None, d_max_length=None, perturb_type="replace")
pert1_dot_dataloader = DataLoader(dataset, batch_size=16, collate_fn=pert1_dot_collator)
pert2_dot_collator = DotDataCollator(dot_model.tokenizer, pert2, q_max_length=None, d_max_length=None, perturb_type="replace")
pert2_dot_dataloader = DataLoader(dataset, batch_size=16, collate_fn=pert2_dot_collator)
![Chart of the impact of a perturbation on the components](images/ActivationPatchingAllHeadExempleMechIR.png) ```
### Visualisation of perturbed data
``` {python}
# Get a single pair from each perturbation type just to visualize
pert1_batch = next(iter(pert1_dot_dataloader))
pert2_batch = next(iter(pert2_dot_dataloader))
print("solution -> answer")
pretty_print_triplets(pert1_batch, dot_model.tokenizer, num=2)
```
```{python}
print("microwave -> toaster")
pretty_print_triplets(pert2_batch, dot_model.tokenizer, num=2)
```
### Step 4 : Measure the impact of the perturbation on the model
```{python}
#|echo: true
# Initialize lists to store baseline and perturbed performances for each dataloader
all_baseline_performance = {"pert1": [], "pert2": []}
all_perturbed_performance = {"pert1": [], "pert2": []}
# Calculate performances for each perturbation_type
calculate_performance(dot_model, pert1_dot_dataloader, all_baseline_performance["pert1"], all_perturbed_performance["pert1"])
calculate_performance(dot_model, pert2_dot_dataloader, all_baseline_performance["pert2"], all_perturbed_performance["pert2"])
plot_score_dists_mult(all_baseline_performance, all_perturbed_performance, plot_type="kde")
```
### Step 5 : Chart the sensitivity of the model to the perturbation
```{python}
patching_head_outputs = []
for i, batch in enumerate(pert2_dot_dataloader):
queries = batch["queries"]
documents = batch["documents"]
perturbed_documents = batch["perturbed_documents"]
patch_head_out = dot_model.patch(queries, documents, perturbed_documents, patch_type="head_all")
patching_head_outputs.append(patch_head_out)
mean_head_outputs = torch.mean(torch.stack([tens for tens,_ in patching_head_outputs]), axis=0)
plot_components(mean_head_outputs.detach().to("cpu").numpy())
```
<!-- ![Chart of the impact of a perturbation on the components](images/ActivationPatchingAllHeadExempleMechIR.png) -->
### Perspective : Enhance a model with MechIR ### Perspective : Enhance a model with MechIR
TODO
### References ### References
::: {#refs} ::: {#refs}
::: :::
## Demonstration (TASB & Vaswani)
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"title: \"Mechanistic interpretability for enhancing RAG models\"\n",
"format: \n",
" revealjs:\n",
" toc: true\n",
" toc-depth: 2\n",
" code-fold: true\n",
" slide-level: 3\n",
" mouse-wheel: true\n",
"jupyter : python3\n",
"style: |\n",
" .columns {\n",
" display: grid;\n",
" grid-template-columns: repeat(2, minmax(0, 1fr));\n",
" gap: 1rem;\n",
" }\n",
" .small {\n",
" font-size: 20px\n",
" }\n",
" .midsize{\n",
" font-size: 25px\n",
" }\n",
"---\n",
"\n",
"## Retrieval Augmented Generation - RAG\n",
"\n",
"### Retrieval Augmented Generation - Definition\n",
"\n",
"![Simple RAG Architecture](images/DefRAG.drawio.png) \n",
"\n",
"![Advanced RAG Achitecture](images/DefRAGAvance_integration.drawio.png)\n",
"\n",
"\n",
"### Approche plus théorique de retriever et generateur\n",
"\n",
"_Retriever comme plongement des documents et questions dans un espace_\n",
"\n",
"_Generateur comme fonction d'une paire (question, ensemble de documents) vers texte_\n",
"\n",
"\n",
"\n",
"### Example\n",
"\n",
"![RAG Architecture used here](images/RAGHN-perso.drawio.png)\n",
"\n",
"## Explainability in Artificial Intelligence\n",
"\n",
"### Explainability in Artificial Intelligence\n",
"\n",
"Aims:\n",
"\n",
"- Trustability\n",
"- Understandability\n",
"- Model Rectification\n",
"\n",
"### Definitions\n",
"\n",
"**XAI** : Make model's behavior understandable for human [@bell_its_2022] \n",
"**Understand** : Predict model's behavior [@bell_its_2022] \n",
"**Explanation** : Any way to make decision process understandable for human\n",
"\n",
":::: {.columns}\n",
"\n",
"::: {.column width=\"40%\"}\n",
"**Interpretability** \n",
"_How ?_\n",
":::\n",
"\n",
"::: {.column width=\"40%\"}\n",
"\n",
"**Explanability** \n",
"_Why ?_\n",
":::\n",
"\n",
"::::\n",
"\n",
"## Explanation through creation of a model\n",
"\n",
"![Explanation through creation of a model](images/VieModele-TempsXAI.drawio.png)\n",
"\n",
"## MechIR [@parry_mechir_2025]\n",
"\n",
"### MechIR [@parry_mechir_2025]\n",
"\n",
"#### Mechanistic interpretability \n",
"Understand the internal mechanisms of neural networks by **performing causal interventions** on specific model components\n",
"\n",
"#### MechIR\n",
"- Encoder-only models \n",
"- For Information Retrieval models\n",
"\n",
"- Identify components responsible for some behavior\n",
"- Activation Patching Technique \n",
"\n",
"### Activation Patching [@chen_axiomatic_2024] {.smaller}\n",
"Let $Q \\times D \\subset \\mathcal{Q}\\times\\mathcal{D}$ be a set of pairs of questions and documents \n",
"Let $Q \\times \\tilde{D}$ the same set of pairs but with perturbed documents \n",
"\n",
"1. Forward pass all $Q\\times D$\n",
" - record $o_{i,j}^e$ the output of each component $n_{i,j}, \\forall e \\in Q\\times D$\n",
" - record $p_D$ the performance of the model\n",
"2. Forward pass all $Q\\times \\tilde{D}$\n",
" - record $o_{i,j}^\\tilde{e}$ the output of each component $n_{i,j}, \\forall \\tilde{e} \\in Q\\times \\tilde{D}$\n",
" - record $p_\\tilde{D}$ the performance of the model \n",
"3. Rewrite $D, e, \\tilde{D} \\text{ and } \\tilde{e}$ as\n",
"- $\\hat{D}, \\hat{e}, \\check{D} \\text{ and } \\check{e}$ if $p_D > p_\\tilde{D}$\n",
"- $\\check{D}, \\check{e}, \\hat{D} \\text{ and } \\hat{e}$ otherwise\n",
"4. For each component $n_{i,j}$ forward pass $Q\\times\\check{D}$ but replace $o_{i,j}^{\\check{e}}$ by $o_{i,j}^{\\hat{e}}$ for each $\\check{e}$. Record the performance $\\bar{p}$\n",
"5. $P = \\frac{\\bar{p} - p_\\hat{D} }{\\p_\\check{D} - p_\\hat{D}}$ gives the impact of the perturbation on the model performance\n",
"\n",
"\n",
"### Animation de l'execution de Activation patching\n",
"\n",
"### Perturbation\n",
"\n",
"Function that applies the same modification on each document.\n",
"Example : "
],
"id": "fa2ddf7d"
},
{
"cell_type": "code",
"metadata": {},
"source": [
"def perturbation(doc):\n",
" return doc.replace(\"microwave\", \"toaster\")"
],
"id": "2898ee6e",
"execution_count": null,
"outputs": []
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"#### Perturbation creation technique\n",
"\n",
"- Identify vocabulary specific to the dataset \n",
"- find in the vocabulary words with several meaning $m_D$ and $m_D$\n",
"- Replace that word by a synonym of the $m_D$ meaning\n",
"\n",
"\n",
"### What is a good perturbation \n",
"\n",
"- Have an impact of the documents representation\n",
"_Des images de courbes à ajouter ici_\n",
"- Be useful for interpretation\n",
"\n",
"### Enhance a model with MechIR\n",
"TODO\n",
"\n",
"\n",
"---"
],
"id": "069b4e0f"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"# Brouillon\n",
"- Mechir\n",
" - but et concept : cartographier les sensibilités des modèles encoder-based \n",
" - Activation Patching [Chen et al,. 2024]\n",
" - Étapes\n",
" - recul sur le résultat obtenu\n",
" - Perturbation\n",
" - Definition\n",
" - approche de création par étude du vocabulaire important et utilisation des mots poly-sémantiques\n",
" - 3 types de perturbation (append, prepend, replace) -> préférer replace\n",
" - identifier une perturbation pertinente\n",
" - Améliorer le modèle\n",
" - Quelle modification effectuer?\n",
" - "
],
"id": "0253d293"
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"language": "python",
"display_name": "Python 3 (ipykernel)",
"path": "/home/marine/miniconda3/share/jupyter/kernels/python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
\ No newline at end of file
{
"cells": [
{
"cell_type": "markdown",
"id": "84d8a3bf",
"metadata": {},
"source": [
"---\n",
"title: \"Mechanistic interpretability for enhancing RAG models\"\n",
"format: \n",
" revealjs:\n",
" toc: true\n",
" toc-depth: 2\n",
" code-fold: true\n",
" slide-level: 3\n",
" mouse-wheel: true\n",
"jupyter : python3\n",
"style: |\n",
" .columns {\n",
" display: grid;\n",
" grid-template-columns: repeat(2, minmax(0, 1fr));\n",
" gap: 1rem;\n",
" }\n",
" .small {\n",
" font-size: 20px\n",
" }\n",
" .midsize{\n",
" font-size: 25px\n",
" }\n",
"---\n",
"\n",
"## Retrieval Augmented Generation - RAG\n",
"\n",
"### Retrieval Augmented Generation - Definition\n",
"\n",
"![Simple RAG Architecture](images/DefRAG.drawio.png) \n",
"\n",
"![Advanced RAG Achitecture](images/DefRAGAvance_integration.drawio.png)\n",
"\n",
"\n",
"### Approche plus théorique de retriever et generateur\n",
"\n",
"_Retriever comme plongement des documents et questions dans un espace_\n",
"\n",
"_Generateur comme fonction d'une paire (question, ensemble de documents) vers texte_\n",
"\n",
"\n",
"\n",
"### Example\n",
"\n",
"![RAG Architecture used here](images/RAGHN-perso.drawio.png)\n",
"\n",
"## Explainability in Artificial Intelligence\n",
"\n",
"### Explainability in Artificial Intelligence\n",
"\n",
"Aims:\n",
"\n",
"- Trustability\n",
"- Understandability\n",
"- Model Rectification\n",
"\n",
"### Definitions\n",
"\n",
"**XAI** : Make model's behavior understandable for human [@bell_its_2022] \n",
"**Understand** : Predict model's behavior [@bell_its_2022] \n",
"**Explanation** : Any way to make decision process understandable for human\n",
"\n",
":::: {.columns}\n",
"\n",
"::: {.column width=\"40%\"}\n",
"**Interpretability** \n",
"_How ?_\n",
":::\n",
"\n",
"::: {.column width=\"40%\"}\n",
"\n",
"**Explanability** \n",
"_Why ?_\n",
":::\n",
"\n",
"::::\n",
"\n",
"## Explanation through creation of a model\n",
"\n",
"![Explanation through creation of a model](images/VieModele-TempsXAI.drawio.png)\n",
"\n",
"## MechIR [@parry_mechir_2025]\n",
"\n",
"### MechIR [@parry_mechir_2025]\n",
"\n",
"#### Mechanistic interpretability \n",
"Understand the internal mechanisms of neural networks by **performing causal interventions** on specific model components\n",
"\n",
"#### MechIR\n",
"- Encoder-only models \n",
"- For Information Retrieval models\n",
"\n",
"- Identify components responsible for some behavior\n",
"- Activation Patching Technique \n",
"\n",
"### Activation Patching [@chen_axiomatic_2024] {.smaller}\n",
"Let $Q \\times D \\subset \\mathcal{Q}\\times\\mathcal{D}$ be a set of pairs of questions and documents \n",
"Let $Q \\times \\tilde{D}$ the same set of pairs but with perturbed documents \n",
"\n",
"1. Forward pass all $Q\\times D$\n",
" - record $o_{i,j}^e$ the output of each component $n_{i,j}, \\forall e \\in Q\\times D$\n",
" - record $p_D$ the performance of the model\n",
"2. Forward pass all $Q\\times \\tilde{D}$\n",
" - record $o_{i,j}^\\tilde{e}$ the output of each component $n_{i,j}, \\forall \\tilde{e} \\in Q\\times \\tilde{D}$\n",
" - record $p_\\tilde{D}$ the performance of the model \n",
"3. Rewrite $D, e, \\tilde{D} \\text{ and } \\tilde{e}$ as\n",
"- $\\hat{D}, \\hat{e}, \\check{D} \\text{ and } \\check{e}$ if $p_D > p_\\tilde{D}$\n",
"- $\\check{D}, \\check{e}, \\hat{D} \\text{ and } \\hat{e}$ otherwise\n",
"4. For each component $n_{i,j}$ forward pass $Q\\times\\check{D}$ but replace $o_{i,j}^{\\check{e}}$ by $o_{i,j}^{\\hat{e}}$ for each $\\check{e}$. Record the performance $\\bar{p}$\n",
"5. $P = \\frac{\\bar{p} - p_\\hat{D} }{\\p_\\check{D} - p_\\hat{D}}$ gives the impact of the perturbation on the model performance\n",
"\n",
"\n",
"### Animation de l'execution de Activation patching\n",
"\n",
"### Perturbation\n",
"\n",
"Function that applies the same modification on each document.\n",
"Example : "
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "d02801b1",
"metadata": {},
"outputs": [],
"source": [
"def perturbation(doc):\n",
" return doc.replace(\"microwave\", \"toaster\")"
]
},
{
"cell_type": "raw",
"id": "a4e2efff",
"metadata": {},
"source": [
"#### Perturbation creation technique\n",
"\n",
"- Identify vocabulary specific to the dataset \n",
"- find in the vocabulary words with several meaning $m_D$ and $m_D$\n",
"- Replace that word by a synonym of the $m_D$ meaning\n",
"\n",
"\n",
"### What is a good perturbation \n",
"\n",
"- Have an impact of the documents representation\n",
"_Des images de courbes à ajouter ici_\n",
"- Be useful for interpretation\n",
"\n",
"### Enhance a model with MechIR\n",
"TODO\n",
"\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"id": "a80fea01",
"metadata": {},
"source": [
"---\n",
"# Brouillon\n",
"- Mechir\n",
" - but et concept : cartographier les sensibilités des modèles encoder-based \n",
" - Activation Patching [Chen et al,. 2024]\n",
" - Étapes\n",
" - recul sur le résultat obtenu\n",
" - Perturbation\n",
" - Definition\n",
" - approche de création par étude du vocabulaire important et utilisation des mots poly-sémantiques\n",
" - 3 types de perturbation (append, prepend, replace) -> préférer replace\n",
" - identifier une perturbation pertinente\n",
" - Améliorer le modèle\n",
" - Quelle modification effectuer?\n",
" - "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3",
"path": "/home/marine/miniconda3/share/jupyter/kernels/python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"title: \"Mechanistic interpretability for enhancing RAG models\"\n",
"format: \n",
" revealjs:\n",
" toc: true\n",
" toc-depth: 2\n",
" code-fold: true\n",
" slide-level: 3\n",
" mouse-wheel: true\n",
"jupyter : python3\n",
"style: |\n",
" .columns {\n",
" display: grid;\n",
" grid-template-columns: repeat(2, minmax(0, 1fr));\n",
" gap: 1rem;\n",
" }\n",
" .small {\n",
" font-size: 20px\n",
" }\n",
" .midsize{\n",
" font-size: 25px\n",
" }\n",
"---\n",
"\n",
"## Retrieval Augmented Generation - RAG\n",
"\n",
"### Retrieval Augmented Generation - Definition\n",
"\n",
"![Simple RAG Architecture](images/DefRAG.drawio.png) \n",
"\n",
"![Advanced RAG Achitecture](images/DefRAGAvance_integration.drawio.png)\n",
"\n",
"\n",
"### Approche plus théorique de retriever et generateur\n",
"\n",
"_Retriever comme plongement des documents et questions dans un espace_\n",
"\n",
"_Generateur comme fonction d'une paire (question, ensemble de documents) vers texte_\n",
"\n",
"\n",
"\n",
"### Example\n",
"\n",
"![RAG Architecture used here](images/RAGHN-perso.drawio.png)\n",
"\n",
"## Explainability in Artificial Intelligence\n",
"\n",
"### Explainability in Artificial Intelligence\n",
"\n",
"Aims:\n",
"\n",
"- Trustability\n",
"- Understandability\n",
"- Model Rectification\n",
"\n",
"### Definitions\n",
"\n",
"**XAI** : Make model's behavior understandable for human [@bell_its_2022] \n",
"**Understand** : Predict model's behavior [@bell_its_2022] \n",
"**Explanation** : Any way to make decision process understandable for human\n",
"\n",
":::: {.columns}\n",
"\n",
"::: {.column width=\"40%\"}\n",
"**Interpretability** \n",
"_How ?_\n",
":::\n",
"\n",
"::: {.column width=\"40%\"}\n",
"\n",
"**Explanability** \n",
"_Why ?_\n",
":::\n",
"\n",
"::::\n",
"\n",
"## Explanation through creation of a model\n",
"\n",
"![Explanation through creation of a model](images/VieModele-TempsXAI.drawio.png)\n",
"\n",
"## MechIR [@parry_mechir_2025]\n",
"\n",
"### MechIR [@parry_mechir_2025]\n",
"\n",
"#### Mechanistic interpretability \n",
"Understand the internal mechanisms of neural networks by **performing causal interventions** on specific model components\n",
"\n",
"#### MechIR\n",
"- Encoder-only models \n",
"- For Information Retrieval models\n",
"\n",
"- Identify components responsible for some behavior\n",
"- Activation Patching Technique \n",
"\n",
"### Activation Patching [@chen_axiomatic_2024] {.smaller}\n",
"Let $Q \\times D \\subset \\mathcal{Q}\\times\\mathcal{D}$ be a set of pairs of questions and documents \n",
"Let $Q \\times \\tilde{D}$ the same set of pairs but with perturbed documents \n",
"\n",
"1. Forward pass all $Q\\times D$\n",
" - record $o_{i,j}^e$ the output of each component $n_{i,j}, \\forall e \\in Q\\times D$\n",
" - record $p_D$ the performance of the model\n",
"2. Forward pass all $Q\\times \\tilde{D}$\n",
" - record $o_{i,j}^\\tilde{e}$ the output of each component $n_{i,j}, \\forall \\tilde{e} \\in Q\\times \\tilde{D}$\n",
" - record $p_\\tilde{D}$ the performance of the model \n",
"3. Rewrite $D, e, \\tilde{D} \\text{ and } \\tilde{e}$ as\n",
"- $\\hat{D}, \\hat{e}, \\check{D} \\text{ and } \\check{e}$ if $p_D > p_\\tilde{D}$\n",
"- $\\check{D}, \\check{e}, \\hat{D} \\text{ and } \\hat{e}$ otherwise\n",
"4. For each component $n_{i,j}$ forward pass $Q\\times\\check{D}$ but replace $o_{i,j}^{\\check{e}}$ by $o_{i,j}^{\\hat{e}}$ for each $\\check{e}$. Record the performance $\\bar{p}$\n",
"5. $P = \\frac{\\bar{p} - p_\\hat{D} }{\\p_\\check{D} - p_\\hat{D}}$ gives the impact of the perturbation on the model performance\n",
"\n",
"\n",
"### Animation de l'execution de Activation patching\n",
"\n",
"### Perturbation\n",
"\n",
"Function that applies the same modification on each document. \n",
"Example : "
],
"id": "99dbc701"
},
{
"cell_type": "code",
"metadata": {},
"source": [
"#| echo: true\n",
"def perturbation(doc):\n",
" return doc.replace(\"microwave\", \"toaster\")"
],
"id": "a87c9cff",
"execution_count": null,
"outputs": []
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"#### Perturbation creation technique\n",
"\n",
"- Identify vocabulary specific to the dataset \n",
"- find in the vocabulary words with several meaning $m_D$ and $m_D$\n",
"- Replace that word by a synonym of the $m_D$ meaning\n",
"\n",
"\n",
"### What is a good perturbation \n",
"\n",
"- Have an impact of the documents representation\n",
"_Des images de courbes à ajouter ici_\n",
"- Be useful for interpretation\n",
"\n",
"### Enhance a model with MechIR\n",
"TODO\n",
"\n",
"\n",
"---"
],
"id": "dab3024c"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"# Brouillon\n",
"- Mechir\n",
" - but et concept : cartographier les sensibilités des modèles encoder-based \n",
" - Activation Patching [Chen et al,. 2024]\n",
" - Étapes\n",
" - recul sur le résultat obtenu\n",
" - Perturbation\n",
" - Definition\n",
" - approche de création par étude du vocabulaire important et utilisation des mots poly-sémantiques\n",
" - 3 types de perturbation (append, prepend, replace) -> préférer replace\n",
" - identifier une perturbation pertinente\n",
" - Améliorer le modèle\n",
" - Quelle modification effectuer?\n",
" - "
],
"id": "310e6897"
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"language": "python",
"display_name": "Python 3 (ipykernel)",
"path": "/home/marine/miniconda3/share/jupyter/kernels/python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
\ No newline at end of file
{
"cells": [
{
"cell_type": "markdown",
"id": "ba85654b",
"metadata": {},
"source": [
"---\n",
"title: \"Mechanistic interpretability for enhancing RAG models\"\n",
"format: \n",
" revealjs:\n",
" toc: true\n",
" toc-depth: 2\n",
" code-fold: true\n",
" slide-level: 3\n",
" mouse-wheel: true\n",
"jupyter : python3\n",
"style: |\n",
" .columns {\n",
" display: grid;\n",
" grid-template-columns: repeat(2, minmax(0, 1fr));\n",
" gap: 1rem;\n",
" }\n",
" .small {\n",
" font-size: 20px\n",
" }\n",
" .midsize{\n",
" font-size: 25px\n",
" }\n",
"---\n",
"\n",
"## Retrieval Augmented Generation - RAG\n",
"\n",
"### Retrieval Augmented Generation - Definition\n",
"\n",
"![Simple RAG Architecture](images/DefRAG.drawio.png) \n",
"\n",
"![Advanced RAG Achitecture](images/DefRAGAvance_integration.drawio.png)\n",
"\n",
"\n",
"### Approche plus théorique de retriever et generateur\n",
"\n",
"_Retriever comme plongement des documents et questions dans un espace_\n",
"\n",
"_Generateur comme fonction d'une paire (question, ensemble de documents) vers texte_\n",
"\n",
"\n",
"\n",
"### Example\n",
"\n",
"![RAG Architecture used here](images/RAGHN-perso.drawio.png)\n",
"\n",
"## Explainability in Artificial Intelligence\n",
"\n",
"### Explainability in Artificial Intelligence\n",
"\n",
"Aims:\n",
"\n",
"- Trustability\n",
"- Understandability\n",
"- Model Rectification\n",
"\n",
"### Definitions\n",
"\n",
"**XAI** : Make model's behavior understandable for human [@bell_its_2022] \n",
"**Understand** : Predict model's behavior [@bell_its_2022] \n",
"**Explanation** : Any way to make decision process understandable for human\n",
"\n",
":::: {.columns}\n",
"\n",
"::: {.column width=\"40%\"}\n",
"**Interpretability** \n",
"_How ?_\n",
":::\n",
"\n",
"::: {.column width=\"40%\"}\n",
"\n",
"**Explanability** \n",
"_Why ?_\n",
":::\n",
"\n",
"::::\n",
"\n",
"## Explanation through creation of a model\n",
"\n",
"![Explanation through creation of a model](images/VieModele-TempsXAI.drawio.png)\n",
"\n",
"## MechIR [@parry_mechir_2025]\n",
"\n",
"### MechIR [@parry_mechir_2025]\n",
"\n",
"#### Mechanistic interpretability \n",
"Understand the internal mechanisms of neural networks by **performing causal interventions** on specific model components\n",
"\n",
"#### MechIR\n",
"- Encoder-only models \n",
"- For Information Retrieval models\n",
"\n",
"- Identify components responsible for some behavior\n",
"- Activation Patching Technique \n",
"\n",
"### Activation Patching [@chen_axiomatic_2024] {.smaller}\n",
"Let $Q \\times D \\subset \\mathcal{Q}\\times\\mathcal{D}$ be a set of pairs of questions and documents \n",
"Let $Q \\times \\tilde{D}$ the same set of pairs but with perturbed documents \n",
"\n",
"1. Forward pass all $Q\\times D$\n",
" - record $o_{i,j}^e$ the output of each component $n_{i,j}, \\forall e \\in Q\\times D$\n",
" - record $p_D$ the performance of the model\n",
"2. Forward pass all $Q\\times \\tilde{D}$\n",
" - record $o_{i,j}^\\tilde{e}$ the output of each component $n_{i,j}, \\forall \\tilde{e} \\in Q\\times \\tilde{D}$\n",
" - record $p_\\tilde{D}$ the performance of the model \n",
"3. Rewrite $D, e, \\tilde{D} \\text{ and } \\tilde{e}$ as\n",
"- $\\hat{D}, \\hat{e}, \\check{D} \\text{ and } \\check{e}$ if $p_D > p_\\tilde{D}$\n",
"- $\\check{D}, \\check{e}, \\hat{D} \\text{ and } \\hat{e}$ otherwise\n",
"4. For each component $n_{i,j}$ forward pass $Q\\times\\check{D}$ but replace $o_{i,j}^{\\check{e}}$ by $o_{i,j}^{\\hat{e}}$ for each $\\check{e}$. Record the performance $\\bar{p}$\n",
"5. $P = \\frac{\\bar{p} - p_\\hat{D} }{\\p_\\check{D} - p_\\hat{D}}$ gives the impact of the perturbation on the model performance\n",
"\n",
"\n",
"### Animation de l'execution de Activation patching\n",
"\n",
"### Perturbation\n",
"\n",
"Function that applies the same modification on each document. \n",
"Example : "
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "70279707",
"metadata": {},
"outputs": [],
"source": [
"#| echo: true\n",
"def perturbation(doc):\n",
" return doc.replace(\"microwave\", \"toaster\")"
]
},
{
"cell_type": "raw",
"id": "d1b08c4e",
"metadata": {},
"source": [
"#### Perturbation creation technique\n",
"\n",
"- Identify vocabulary specific to the dataset \n",
"- find in the vocabulary words with several meaning $m_D$ and $m_D$\n",
"- Replace that word by a synonym of the $m_D$ meaning\n",
"\n",
"\n",
"### What is a good perturbation \n",
"\n",
"- Have an impact of the documents representation\n",
"_Des images de courbes à ajouter ici_\n",
"- Be useful for interpretation\n",
"\n",
"### Enhance a model with MechIR\n",
"TODO\n",
"\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"id": "3f975028",
"metadata": {},
"source": [
"---\n",
"# Brouillon\n",
"- Mechir\n",
" - but et concept : cartographier les sensibilités des modèles encoder-based \n",
" - Activation Patching [Chen et al,. 2024]\n",
" - Étapes\n",
" - recul sur le résultat obtenu\n",
" - Perturbation\n",
" - Definition\n",
" - approche de création par étude du vocabulaire important et utilisation des mots poly-sémantiques\n",
" - 3 types de perturbation (append, prepend, replace) -> préférer replace\n",
" - identifier une perturbation pertinente\n",
" - Améliorer le modèle\n",
" - Quelle modification effectuer?\n",
" - "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3",
"path": "/home/marine/miniconda3/share/jupyter/kernels/python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment