<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Blog on Kosmo CHE</title><link>https://kosmoche.github.io/blog/</link><description>Recent content in Blog on Kosmo CHE</description><generator>Hugo -- 0.146.3</generator><language>en</language><copyright>2024-2026 Kosmo CHE</copyright><atom:link href="https://kosmoche.github.io/blog/index.xml" rel="self" type="application/rss+xml"/><item><title>Tips on Server(The suck jupyter kernel)</title><link>https://kosmoche.github.io/blogs/tips_on_server/</link><pubDate>Tue, 11 Nov 2025 19:29:20 +0800</pubDate><guid>https://kosmoche.github.io/blogs/tips_on_server/</guid><description>This blog is to note some tips and command lines for server management and Jupyter usage.</description><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>Some commands and tips, often used when working on a server, I feel tired of asking gpt again and again.</p>
<h3 id="1-kill-jupyter-notebook-kernel">1. Kill Jupyter Notebook Kernel</h3>
<p>When you use Jupyter Notebook on a server,especially when in VSCode, sometimes the kernel may get stuck or become unresponsive.
Unfortunately, VSCode does not provide a direct way to kill or shutdown the kernel from its interface.This make a lot of jupyter processes running on the server, consuming resources and causing confusion.</p>
<p>Check the running Jupyter processes with:</p>




<div class="pe-code-block-wrap  pe-code-details   scrollable">
    <div class="pe-code-block-header pe-code-details-summary">
        <div class="pe-code-block-header-left">
            <div class="mac-dots"></div>
            
            <span>bash
            </span>
            
        </div>
        <div class="pe-code-block-header-center">
            <span>
            </span>
        </div>
        <div class="pe-code-block-header-right">
             
            <svg xmlns="http://www.w3.org/2000/svg" class="arrow pe-code-details-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path fill="currentColor" d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
            </svg>
            
            <button class="pe-code-copy-button">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" class="pe-icon"><path fill="currentColor" fill-rule="evenodd" d="M7 5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-2v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3h2zm2 2h5a3 3 0 0 1 3 3v5h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-9a1 1 0 0 0-1 1zM5 9a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1z" clip-rule="evenodd"></path></svg>
            </button>
        </div>
    </div>
    <div class="pe-code-details-content scrollable">
        <div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">pgrep -a -u username -f jupyter</span></span></code></pre></td></tr></table>
</div>
</div>
    </div>
</div><p>and then kill</p>




<div class="pe-code-block-wrap  pe-code-details   scrollable">
    <div class="pe-code-block-header pe-code-details-summary">
        <div class="pe-code-block-header-left">
            <div class="mac-dots"></div>
            
            <span>bash
            </span>
            
        </div>
        <div class="pe-code-block-header-center">
            <span>
            </span>
        </div>
        <div class="pe-code-block-header-right">
             
            <svg xmlns="http://www.w3.org/2000/svg" class="arrow pe-code-details-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path fill="currentColor" d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
            </svg>
            
            <button class="pe-code-copy-button">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" class="pe-icon"><path fill="currentColor" fill-rule="evenodd" d="M7 5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-2v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3h2zm2 2h5a3 3 0 0 1 3 3v5h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-9a1 1 0 0 0-1 1zM5 9a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1z" clip-rule="evenodd"></path></svg>
            </button>
        </div>
    </div>
    <div class="pe-code-details-content scrollable">
        <div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nb">kill</span> -9 PID</span></span></code></pre></td></tr></table>
</div>
</div>
    </div>
</div><p>And if you want to be more aggressive, the most brutal method is:</p>




<div class="pe-code-block-wrap  pe-code-details   scrollable">
    <div class="pe-code-block-header pe-code-details-summary">
        <div class="pe-code-block-header-left">
            <div class="mac-dots"></div>
            
            <span>bash
            </span>
            
        </div>
        <div class="pe-code-block-header-center">
            <span>
            </span>
        </div>
        <div class="pe-code-block-header-right">
             
            <svg xmlns="http://www.w3.org/2000/svg" class="arrow pe-code-details-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path fill="currentColor" d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
            </svg>
            
            <button class="pe-code-copy-button">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" class="pe-icon"><path fill="currentColor" fill-rule="evenodd" d="M7 5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-2v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3h2zm2 2h5a3 3 0 0 1 3 3v5h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-9a1 1 0 0 0-1 1zM5 9a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1z" clip-rule="evenodd"></path></svg>
            </button>
        </div>
    </div>
    <div class="pe-code-details-content scrollable">
        <div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">pkill -9 -u username -f jupyter</span></span></code></pre></td></tr></table>
</div>
</div>
    </div>
</div><h3 id="2-check-processes">2. Check Processes</h3>
<p>To check all the processes running under your username, you can use:</p>




<div class="pe-code-block-wrap  pe-code-details   scrollable">
    <div class="pe-code-block-header pe-code-details-summary">
        <div class="pe-code-block-header-left">
            <div class="mac-dots"></div>
            
            <span>bash
            </span>
            
        </div>
        <div class="pe-code-block-header-center">
            <span>
            </span>
        </div>
        <div class="pe-code-block-header-right">
             
            <svg xmlns="http://www.w3.org/2000/svg" class="arrow pe-code-details-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path fill="currentColor" d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
            </svg>
            
            <button class="pe-code-copy-button">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" class="pe-icon"><path fill="currentColor" fill-rule="evenodd" d="M7 5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-2v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3h2zm2 2h5a3 3 0 0 1 3 3v5h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-9a1 1 0 0 0-1 1zM5 9a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1z" clip-rule="evenodd"></path></svg>
            </button>
        </div>
    </div>
    <div class="pe-code-details-content scrollable">
        <div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">ps -u username -o pid,ppid,cmd,%mem,%cpu --sort<span class="o">=</span>-rss <span class="p">|</span> head -n <span class="m">20</span></span></span></code></pre></td></tr></table>
</div>
</div>
    </div>
</div><p>This command will show you the top 20 processes consuming the most memory, along with their PID, parent PID, command, memory usage, and CPU usage.</p>
<p>To check all the processes running on the server, you can use:</p>




<div class="pe-code-block-wrap  pe-code-details   scrollable">
    <div class="pe-code-block-header pe-code-details-summary">
        <div class="pe-code-block-header-left">
            <div class="mac-dots"></div>
            
            <span>bash
            </span>
            
        </div>
        <div class="pe-code-block-header-center">
            <span>
            </span>
        </div>
        <div class="pe-code-block-header-right">
             
            <svg xmlns="http://www.w3.org/2000/svg" class="arrow pe-code-details-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path fill="currentColor" d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
            </svg>
            
            <button class="pe-code-copy-button">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" class="pe-icon"><path fill="currentColor" fill-rule="evenodd" d="M7 5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-2v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3h2zm2 2h5a3 3 0 0 1 3 3v5h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-9a1 1 0 0 0-1 1zM5 9a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1z" clip-rule="evenodd"></path></svg>
            </button>
        </div>
    </div>
    <div class="pe-code-details-content scrollable">
        <div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">ps -a -o pid,ppid,user,cmd,%mem,%cpu --sort<span class="o">=</span>-rss <span class="p">|</span> head -n <span class="m">20</span></span></span></code></pre></td></tr></table>
</div>
</div>
    </div>
</div><p>This command will show you the top 20 processes consuming the most memory, along with their PID, parent PID, user, command, memory usage, and CPU usage.</p>
<blockquote>
<p>Let me see who&rsquo;s zombie processes occupying the server resources. 💢</p></blockquote>
]]></content:encoded></item><item><title>RL4LLM: 2. PPO Algorithm and Implementation Details</title><link>https://kosmoche.github.io/blogs/ppo-algorithm-and-implementations/</link><pubDate>Mon, 21 Jul 2025 19:58:49 +0800</pubDate><guid>https://kosmoche.github.io/blogs/ppo-algorithm-and-implementations/</guid><description>This blog post introduces RLHF-PPO algorithm with code implementation.</description><content:encoded><![CDATA[<h2 id="1-overview-of-ppo-implementation">1. Overview of PPO Implementation</h2>
<p>The simplified code for the RLHF with PPO algorithm in <strong>TRL</strong> is as follows:</p>




<div class="pe-code-block-wrap  pe-code-details   scrollable">
    <div class="pe-code-block-header pe-code-details-summary">
        <div class="pe-code-block-header-left">
            <div class="mac-dots"></div>
            
            <span>python
            </span>
            
        </div>
        <div class="pe-code-block-header-center">
            <span>The simplified code of PPO
            
            </span>
        </div>
        <div class="pe-code-block-header-right">
             
            <svg xmlns="http://www.w3.org/2000/svg" class="arrow pe-code-details-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path fill="currentColor" d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
            </svg>
            
            <button class="pe-code-copy-button">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" class="pe-icon"><path fill="currentColor" fill-rule="evenodd" d="M7 5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-2v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3h2zm2 2h5a3 3 0 0 1 3 3v5h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-9a1 1 0 0 0-1 1zM5 9a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1z" clip-rule="evenodd"></path></svg>
            </button>
        </div>
    </div>
    <div class="pe-code-details-content scrollable">
        <div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">for</span> <span class="n">batch</span> <span class="ow">in</span> <span class="n">dataloader</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Sample</span>
</span></span><span class="line"><span class="cl">    <span class="k">with</span> <span class="n">torch</span><span class="o">.</span><span class="n">no_grad</span><span class="p">():</span>
</span></span><span class="line"><span class="cl">        <span class="n">old_policy_outputs</span><span class="p">,</span><span class="n">logprobs_old_policy</span> <span class="o">=</span> <span class="n">policy_model</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">logprobs_reference</span> <span class="o">=</span> <span class="n">reference_model</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">scores</span> <span class="o">=</span> <span class="n">reward_model</span><span class="p">(</span><span class="n">query</span><span class="o">+</span><span class="n">old_policy_outputs</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">values</span> <span class="o">=</span> <span class="n">value_model</span><span class="p">(</span><span class="n">query</span><span class="o">+</span><span class="n">old_policy_outputs</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="n">kl</span> <span class="o">=</span> <span class="n">logprobs_old_policy</span> <span class="o">-</span> <span class="n">logprobs_reference</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># reward function have different implementation methods</span>
</span></span><span class="line"><span class="cl">        <span class="n">rewards</span> <span class="o">=</span> <span class="n">scores</span> <span class="o">-</span> <span class="n">kl</span> <span class="o">*</span> <span class="n">kl_coef</span> 
</span></span><span class="line"><span class="cl">        <span class="n">lastgaelam</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">        <span class="n">advantages_reversed</span> <span class="o">=</span> <span class="p">[]</span>
</span></span><span class="line"><span class="cl">        <span class="n">gen_length</span> <span class="o">=</span> <span class="n">responses</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># cal advantages</span>
</span></span><span class="line"><span class="cl">        <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="n">gen_length</span><span class="p">)):</span>
</span></span><span class="line"><span class="cl">            <span class="n">nextvalues</span> <span class="o">=</span> <span class="n">values</span><span class="p">[:,</span> <span class="n">t</span> <span class="o">+</span> <span class="mi">1</span><span class="p">]</span> <span class="k">if</span> <span class="n">t</span> <span class="o">&lt;</span> <span class="n">gen_length</span> <span class="o">-</span> <span class="mi">1</span> <span class="k">else</span> <span class="mf">0.0</span>
</span></span><span class="line"><span class="cl">            <span class="n">delta</span> <span class="o">=</span> <span class="n">rewards</span><span class="p">[:,</span> <span class="n">t</span><span class="p">]</span> <span class="o">+</span> <span class="n">args</span><span class="o">.</span><span class="n">gamma</span> <span class="o">*</span> <span class="n">nextvalues</span> <span class="o">-</span> <span class="n">values</span><span class="p">[:,</span> <span class="n">t</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">            <span class="n">lastgaelam</span> <span class="o">=</span> <span class="n">delta</span> <span class="o">+</span> <span class="n">args</span><span class="o">.</span><span class="n">gamma</span> <span class="o">*</span> <span class="n">args</span><span class="o">.</span><span class="n">lam</span> <span class="o">*</span> <span class="n">lastgaelam</span>
</span></span><span class="line"><span class="cl">            <span class="n">advantages_reversed</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">lastgaelam</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">advantages</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">stack</span><span class="p">(</span><span class="n">advantages_reversed</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">],</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">returns</span> <span class="o">=</span> <span class="n">advantages</span> <span class="o">+</span> <span class="n">values</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Train</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">ppo_epoch_idx</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">num_ppo_epochs</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="n">logprobs_new_policy</span><span class="p">,</span> <span class="n">v_pred</span> <span class="o">=</span> <span class="n">policy_model</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># compute value_loss</span>
</span></span><span class="line"><span class="cl">        <span class="n">v_pred_clipped</span> <span class="o">=</span> <span class="n">clip</span><span class="p">(</span><span class="n">v_pred</span><span class="p">,</span> 
</span></span><span class="line"><span class="cl">                            <span class="n">values</span> <span class="o">-</span> <span class="n">cliprange_value</span><span class="p">,</span> 
</span></span><span class="line"><span class="cl">                            <span class="n">values</span> <span class="o">+</span> <span class="n">cliprange_value</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">vf_loss1</span> <span class="o">=</span> <span class="p">(</span><span class="n">v_pred</span> <span class="o">-</span> <span class="n">returns</span><span class="p">)</span> <span class="o">**</span> <span class="mi">2</span>
</span></span><span class="line"><span class="cl">        <span class="n">vf_loss2</span> <span class="o">=</span> <span class="p">(</span><span class="n">v_pred_clipped</span> <span class="o">-</span> <span class="n">returns</span><span class="p">)</span> <span class="o">**</span> <span class="mi">2</span>
</span></span><span class="line"><span class="cl">        <span class="n">vf_loss</span> <span class="o">=</span> <span class="mf">0.5</span> <span class="o">*</span> <span class="n">torch</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">vf_loss1</span><span class="p">,</span> <span class="n">vf_loss2</span><span class="p">)</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># compute policy_loss</span>
</span></span><span class="line"><span class="cl">        <span class="n">important_ratio</span> <span class="o">=</span> <span class="n">logprobs_new_policy</span> <span class="o">-</span> <span class="n">logprobs_old_policy</span>
</span></span><span class="line"><span class="cl">        <span class="n">policy_loss1</span> <span class="o">=</span> <span class="o">-</span><span class="p">(</span><span class="n">exp</span><span class="p">(</span><span class="n">important_ratio</span><span class="p">)</span> <span class="o">*</span> <span class="n">advantages</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">policy_loss2</span> <span class="o">=</span> <span class="o">-</span><span class="p">(</span><span class="n">clip</span><span class="p">(</span><span class="n">exp</span><span class="p">(</span><span class="n">important_ratio</span><span class="p">),</span> 
</span></span><span class="line"><span class="cl">                            <span class="mf">1.0</span> <span class="o">-</span> <span class="n">cliprange_ratio</span><span class="p">,</span> 
</span></span><span class="line"><span class="cl">                            <span class="mf">1.0</span> <span class="o">+</span> <span class="n">cliprange_ratio</span><span class="p">)</span> \ 
</span></span><span class="line"><span class="cl">                        <span class="o">*</span> <span class="n">advantages</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="n">policy_loss</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">policy_loss1</span><span class="p">,</span> <span class="n">policy_loss2</span><span class="p">)</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">        <span class="n">loss</span> <span class="o">=</span> <span class="n">policy_loss</span> <span class="o">+</span> <span class="n">vf_loss</span> <span class="o">*</span> <span class="n">args</span><span class="o">.</span><span class="n">vf_coef</span></span></span></code></pre></td></tr></table>
</div>
</div>
    </div>
</div><h2 id="2-theory">2. Theory</h2>
<p>To express the PPO algorithm explicitly, I will ignore the <strong>kl-penalty term</strong> and <strong>clip operation</strong> for simplicity.</p>
<h3 id="21-policy-loss">2.1. Policy Loss</h3>
<h4 id="211-policy-gradient">2.1.1 Policy Gradient</h4>
<p>The optimization objective of reinforcement learning is to maximize the expected return:
</p>
$$\max_{\pi_\theta}\mathcal{J}(\pi_\theta) = \mathbb{E}_{\tau \sim \pi_\theta}[R(\tau)]= \sum_\tau R(\tau)P(\tau|\pi_\theta) \tag{Eq 1}$$<p>where $\tau$ is a trajectory sampled from the policy $\pi_\theta$, and $R(\tau)$ is the return of the trajectory.</p>
<p>Then the policy gradient can be derived as follows(details can be found in the <a href="https://zhuanlan.zhihu.com/p/7461863937">[1]</a>):
</p>
$$
\begin{align*}
\nabla_{\theta}\mathcal{J}(\pi_\theta) &= \mathbb{E}_{\tau \sim \pi_\theta}[R(\tau)\nabla log(P(\tau|\pi_\theta))] \\
& = \mathbb{E}_{\tau \sim \pi_\theta}[R(\tau) \sum_{t=0}^{T_n-1}\nabla log(\pi_\theta(a_t|s_t))] \tag{Eq 2}
\end{align*}
$$<p>
where $T_n$ is the length of the trajectory, and $s$ is the state at time step $t$.</p>
<h4 id="212-improvement-of-----gae">2.1.2. Improvement of  $R(\tau)$ - GAE</h4>
<p>As we consider Eq 2, the return $R(\tau)$ is a sum of rewards on the trajectory, but the $\pi_\theta(a|s)$ is a probability distribution on single step. We may think this is not a good choice to use the sum of rewards as the return. In fact there are many ways to improve the return $R(\tau)$, but the most common one is Generalized Advantage Estimation (GAE).</p>
$$
\begin{align*}
&\delta_\phi(s_t,a_t) = r_t +\gamma V_\phi(s_{t+1}) - V_\phi(s_t) \\
&A_\phi(s_t,a_t)=\sum_{l=0}^{\infty}(\gamma \lambda)^l \delta_\phi(s_{t+l},a_{t+l}) \tag{Eq 3}
\end{align*}
$$<p>where $A_\phi(s_t,a_t)$ is the advantage function, $r_t$ is the reward at time step $t$, $\gamma$ is the discount factor, and $V_\phi(s)$ is the value function.</p>
<p>The new policy gradient can be written as:
</p>
$$
\nabla_{\theta}\mathcal{J}(\pi_\theta) = \mathbb{E}_{\tau \sim \pi_\theta}[\sum_{t=0}^{T_n-1} A_\phi(s_t,a_t)\nabla log(\pi_\theta(a_t|s_t))] \tag{Eq 4}
$$<p>According to the gradient Eq 4, we can get the new optimization objective:
</p>
$$
\begin{align*}
\max_{\pi_\theta}\mathcal{J}(\pi_\theta) &= \mathbb{E}_{\tau \sim \pi_\theta}[\sum_{t=0}^{T_n-1} A_\phi(s_t,a_t) log(\pi_\theta(a_t|s_t))] \\
& \approx \frac{1}{N}\sum_{n=1}^{N}\sum_{t=0}^{T_n-1} A_\phi(s_t,a_t) log(\pi_\theta(a_t|s_t)) \\
\Leftrightarrow \max_{\pi_\theta}\mathcal{J}(\pi_\theta) & = \frac{1}{\sum_{n=1}^{N} T_n} \sum_{n=1}^{N}\sum_{t=0}^{T_n-1}A_\phi(s_t,a_t) log(\pi_\theta(a_t|s_t)) \\
&= \mathbb{E}_t[A_\phi(s_t,a_t) log(\pi_\theta(a_t|s_t))]  \tag{Eq 5}
\end{align*}
$$<p>Because the solution is equal between the expectation of the trajectory $\tau$ and the expectation of the time step $t$, we can derive line 2 to line3 in Eq 5.</p>
<h4 id="213-importance-sampling">2.1.3. Importance Sampling</h4>
<p>In the above equation, we can see that the policy gradient is computed by the advantage function and the log probability of the action taken by the policy. However, in practice, we often have a <strong>old policy</strong> $\pi_{\text{old}}(a|s)$, which is used to generate the trajectory $\tau$. We will use these trajectories to update the policy $\pi_\theta(a|s)$ for <code>ppo_epochs</code> times.</p>
<p>The Policy Gradient can be rewritten as:
</p>
$$
\begin{align*}
\nabla_{\theta}\mathcal{J}(\pi_\theta) &= \mathbb{E}_t[A_\phi(s_t,a_t)\nabla log(\pi_\theta(a_t|s_t))]\\
&=\mathop{\mathbb{E}_t}\limits_{\tau \sim \pi_{\text{old}}}[ \frac{\pi_\theta(a_t|s_t)}{\pi_{\text{old}}(a_t|s_t)} A_\phi(s_t,a_t)\nabla log(\pi_\theta(a_t|s_t)) ] \tag{Eq 6}
\end{align*}
$$<p>At last, we can get the final optimization objective:
</p>
$$
\mathcal{J}(\pi_\theta) = \mathop{\mathbb{E}_t}\limits_{\tau \sim \pi_{\text{old}}}[A_\phi(s_t,a_t) \frac{\pi_\theta(a_t|s_t)}{\pi_{\text{old}}(a_t|s_t)}] \tag{Eq 7}
$$<h3 id="22-critic-loss">2.2 Critic Loss</h3>
$$
\mathcal{L}_{\text{critic}} = \mathbb{E}_t[(V_\phi(s_t) - A_\phi(s_t,a_t)-V_{\text{old}}(s_t))^2] \tag{Eq 8}
$$<h2 id="references">References</h2>
<ol>
<li>猛猿. <a href="https://zhuanlan.zhihu.com/p/7461863937" target="_blank" rel="noopener noreferrer">
    人人都能看懂的RL-PPO理论知识
</a>
.</li>
<li>TRL: <a href="https://github.com/huggingface/trl/blob/44e6c153a517ebe6da572ad3c882cbe1e90629b6/trl/trainer/ppo_trainer.py#L412" target="_blank" rel="noopener noreferrer">
    PPO Trainer Implementation
</a>
.</li>
</ol>
]]></content:encoded></item><item><title>Zotero</title><link>https://kosmoche.github.io/blogs/zotero/</link><pubDate>Sun, 13 Jul 2025 21:39:10 +0800</pubDate><guid>https://kosmoche.github.io/blogs/zotero/</guid><description>This blog note how to use Zotero with iCloud as the storage.</description><content:encoded><![CDATA[<h2 id="storage-on-icloud">Storage on iCloud</h2>




<div class="pe-code-block-wrap  pe-code-details   scrollable">
    <div class="pe-code-block-header pe-code-details-summary">
        <div class="pe-code-block-header-left">
            <div class="mac-dots"></div>
            
            <span>bash
            </span>
            
        </div>
        <div class="pe-code-block-header-center">
            <span>
            </span>
        </div>
        <div class="pe-code-block-header-right">
             
            <svg xmlns="http://www.w3.org/2000/svg" class="arrow pe-code-details-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <path fill="currentColor" d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
            </svg>
            
            <button class="pe-code-copy-button">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" class="pe-icon"><path fill="currentColor" fill-rule="evenodd" d="M7 5a3 3 0 0 1 3-3h9a3 3 0 0 1 3 3v9a3 3 0 0 1-3 3h-2v2a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3h2zm2 2h5a3 3 0 0 1 3 3v5h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1h-9a1 1 0 0 0-1 1zM5 9a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1z" clip-rule="evenodd"></path></svg>
            </button>
        </div>
    </div>
    <div class="pe-code-details-content scrollable">
        <div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nb">cd</span> /Users/&lt;username&gt;/Zotero
</span></span><span class="line"><span class="cl">ln -s /Users/&lt;username&gt;/Library/Mobile<span class="se">\ </span>Documents/com~apple~CloudDocs/zotero_storage storage</span></span></code></pre></td></tr></table>
</div>
</div>
    </div>
</div><h2 id="reference">Reference</h2>
<ol>
<li>Xi Chen. <a href="https://notarocketscientist.xyz/posts/2022-10-04-using-zotero-with-icloud-as-the-storage/" target="_blank" rel="noopener noreferrer">
    Using Zotero With iCloud As The Storage
</a>
.</li>
<li>Northword and l0o0<a href="https://zotero-chinese.com/user-guide/plugins/translate/baidu#_4-2-%E7%99%BE%E5%BA%A6%E5%9E%82%E7%9B%B4%E9%A2%86%E5%9F%9F-%E9%A2%86%E5%9F%9F%E7%BF%BB%E8%AF%91-%E8%AE%BE%E7%BD%AE" target="_blank" rel="noopener noreferrer">
    Zotero 中文社区-百度翻译接口申请和配置
</a>
.</li>
</ol>
]]></content:encoded></item><item><title>RL4LLM: 1. A Brief Talk on DPO</title><link>https://kosmoche.github.io/blogs/a-brief-talk-on-dpo/</link><pubDate>Sat, 12 Jul 2025 00:58:24 +0800</pubDate><guid>https://kosmoche.github.io/blogs/a-brief-talk-on-dpo/</guid><description>This blog post notes my understanding of Direct Preference Optimization and the math derivation behind it.</description><content:encoded><![CDATA[<h2 id="motivation-and-overview">Motivation and Overview</h2>
<p>Before we start the derivation in detail, we first introduce the motivation and overview of DPO.</p>
<p>In RLHF, we first need to train a reward model to predict the reward of a response given a prompt. Then, we use the reward model to train the policy model under the restriction of the reference model. However, this two-step process is not very efficient. Especially, we at least need to maintain two model weights, the reward model and the reference model,and train one model or maybe two models at the same time.</p>
<p>To address this issue, DPO proposes a more efficient approach by directly optimizing the policy model in the processing when training the reward model.</p>
<h2 id="derivation">Derivation</h2>
<p>We start with the objective function of the reward model, the most popular choice to model human preferences is Bradley-Terry (BT) model,can be written as:</p>
$$
p^*(y_1 \succ y_2 | x) = \frac{\exp(r^*(x, y_1))}{\exp(r^*(x, y_1)) + \exp(r^*(x, y_2))} \tag{Eq 1}
$$<p>The reward model is trained to maximize the likelihood of the preference data, which can be written as:</p>
$$
\mathcal{L}_{R}(r_{\phi}, \mathcal{D}) = -\mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \log \sigma(r_{\phi}(x, y_w) - r_{\phi}(x, y_l)) \tag{Eq 2}
$$<p>To optimize the policy model in the same time, we need to find a way to convert the reward model into a policy model. In other words, we need to find a way to express the policy model $\pi_{\theta}(y|x)$ in terms of the reward model $r_{\phi}(x, y)$.</p>
<p>All RLHF algorithms can be summarized as the following optimization problem:</p>
$$
\max_{\pi_{\theta}} \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_{\theta}(y|x)} [r_{\phi}(x, y)] - \beta \mathbb{D}_{KL}(\pi_{\theta}(y|x) || \pi_{\text{ref}}(y|x)) \tag{Eq 3}
$$<p>where $\beta$ is a hyperparameter to control the trade-off between the reward and the KL divergence, $r_{\phi}(x, y)$ is the reward model, and $\pi_{\text{ref}}(y|x)$ is the reference model.</p>
<p>To solve this optimization problem(Eq 3), we can get the optimal policy model $p^*(y|x)$ expressed by the reward model $r_\phi(x, y)$.
</p>
$$
\begin{align*}
&\max_{\pi_{\theta}} \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_{\theta}(y|x)} [r_{\phi}(x, y)] - \beta \mathbb{D}_{KL}(\pi_{\theta}(y|x) || \pi_{\text{ref}}(y|x)) \\
& =\max _{\pi_{\theta}} \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_{\theta}(y|x)} [r_{\phi}(x, y) - \beta \log \frac{\pi_{\theta}(y|x)}{\pi_{\text{ref}}(y|x)}] \\
& = \min_{\pi_{\theta}} \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_{\theta}(y|x)} [\log \frac{\pi_{\theta}(y|x)}{\pi_{\text{ref}}(y|x)} - \frac{1}{\beta}r_{\phi}(x, y)] \\
&= \min_{\pi_{\theta}} \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_{\theta}(y|x)} [\log \frac{\pi_{\theta}(y|x)}{\pi_{\text{ref}}(y|x) \exp \left (\frac{1}{\beta}r_{\phi}(x, y)\right)}] \tag{Eq 4}
\end{align*}
$$<p>Now, we find the <strong>Eq 4 like a KL divergence term which is easy for us to optimize</strong>, but with a non-probability distribution in the denominator. So we need to convert the non-probability distribution into a probability distribution by add a normalization term $Z(x)$, which is the partition function:</p>
$$
Z(x) = \sum_y \pi_{\text{ref}}(y|x) \exp\left(\frac{1}{\beta}r_{\phi}(x, y)\right) \tag{Eq 5}
$$<p>so that we can rewrite the denominator as:
</p>
$$
\begin{align*}
\pi_{\text{ref}}(y|x) \exp\left(\frac{1}{\beta}r_{\phi}(x, y)\right) &= \pi_{\text{ref}}(y|x) \exp\left(\frac{1}{\beta}r_{\phi}(x, y)\right) Z(x)^{-1} Z(x) \\
&= \pi^*(y|x) Z(x) \tag{Eq 6}
\end{align*}
$$<p>where $\pi^*(y|x) = \frac {\pi_{\text{ref}}(y|x) \exp\left(\frac{1}{\beta}r_{\phi}(x, y)\right)}{\sum_y \pi_{\text{ref}}(y|x) \exp\left(\frac{1}{\beta}r_{\phi}(x, y)\right)}$, means the probability distribution of the reference model after being re-weighted by the reward function.</p>
<p>we substitute Eq 6 into Eq 4:</p>
$$
\begin{align*}
&\min_{\pi_{\theta}} \mathbb{E}_{x \sim \mathcal{D}, y \sim \pi_{\theta}(y|x)} [\log \frac{\pi_{\theta}(y|x)}{\pi^*(y|x)} - \log Z(x)]\\
&= \min_{\pi_{\theta}} \mathbb{E}_{x \sim \mathcal{D}} [\mathbb{D}_{KL}(\pi_{\theta}(y|x) || \pi^*(y|x)) - \log Z(x)] \tag{Eq 7}
\end{align*}
$$<p>Because the second term is a constant, we can ignore it, and the KL-divergence is minimized at 0 when $\pi_{\theta}(y|x) = \pi^*(y|x)$, the Explicit Solution of the optimal policy model is:</p>
$$
\pi_{\theta}(y|x)=\pi^*(y|x) = \frac {\pi_{\text{ref}}(y|x) \exp\left(\frac{1}{\beta}r_{\phi}(x, y)\right)}{Z(x)} \tag{Eq 8}
$$<p>However, we can not directly use this solution to train the policy model, because computing the partition function $Z(x)$ is expensive.</p>
<p>According to Eq 8, We can get:
</p>
$$
r_{\phi}(x, y) = \beta \log \frac{\pi_{\theta}(y|x)}{\pi_{\text{ref}}(y|x)} + \beta \log Z(x) \tag{Eq 9}
$$<p>Finally, we substitute the Eq 9 into the loss function for reward model Eq 2, we can get the loss function for the policy model:
</p>
$$
\mathcal{L}_{\text{DPO}}(\pi_{\theta}; \pi_{\text{ref}}) = - \mathbb{E}_{(x, y_w, y_l) \sim \mathcal{D}} \log \sigma \left( \beta \log \frac{\pi_{\theta}(y_w | x)}{\pi_{\text{ref}}(y_w | x)} - \beta \log \frac{\pi_{\theta}(y_l | x)}{\pi_{\text{ref}}(y_l | x)} \right) \tag{Eq 10}
$$<h2 id="reference">Reference</h2>
<ol>
<li>Rafailov, Rafael, et al. &ldquo;Direct preference optimization: Your language model is secretly a reward model.&rdquo; Advances in neural information processing systems 36 (2023): 53728-53741.</li>
<li>猛猿. <a href="https://zhuanlan.zhihu.com/p/721073733" target="_blank" rel="noopener noreferrer">
    人人都能看懂的DPO数学原理
</a>
.</li>
<li>SmallerFL. <a href="https://zhuanlan.zhihu.com/p/779691018" target="_blank" rel="noopener noreferrer">
    Direct Preference Optimization (DPO) 原理详解及公式推导
</a>
.</li>
</ol>
]]></content:encoded></item></channel></rss>