<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mahadir Ahmad on Medium]]></title>
        <description><![CDATA[Stories by Mahadir Ahmad on Medium]]></description>
        <link>https://medium.com/@mahadir.ahmad?source=rss-f8a461eb6548------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gv3lqMPLnJJHNlokupwd9g.png</url>
            <title>Stories by Mahadir Ahmad on Medium</title>
            <link>https://medium.com/@mahadir.ahmad?source=rss-f8a461eb6548------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:44:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahadir.ahmad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PHP2Shell: A Deep Dive into the Remote Code Execution Bug That Shook the Web]]></title>
            <link>https://medium.com/@mahadir.ahmad/php2shell-a-deep-dive-into-the-remote-code-execution-bug-that-shook-the-web-d85731d84944?source=rss-f8a461eb6548------2</link>
            <guid isPermaLink="false">https://medium.com/p/d85731d84944</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Mahadir Ahmad]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 08:10:56 GMT</pubDate>
            <atom:updated>2026-10-28T08:10:56.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A blue PHP elephant stands inside a dark metal cage with a large hole in its bars; green binary digits and red warning lights fill the server-room background." src="https://cdn-images-1.medium.com/max/1024/1*FAHwmKf1a1ZZb7OWwpG_Fg.jpeg" /></figure><p>PHP2Shell has been all over security news this week. The PHP Foundation <a href="https://thephp.foundation/blog/2026/10/21/todays-php-security-release-and-how-were-strengthening-php-security/">urged administrators to update PHP immediately</a>. Some warnings went as far as telling operators to <a href="https://www.itpro.com/security/fixes-issued-for-critical-php-vulnerabilities-security-agencies-warn-patch-now-or-take-systems-offline">take affected systems offline until they could patch</a>. That is an extreme response to a software bug. What can PHP2Shell actually do?</p><p>PHP2Shell was <a href="https://thephp.foundation/blog/2026/10/21/todays-php-security-release-and-how-were-strengthening-php-security/">rated 9.2</a> for severity. Its reported chain can reach remote code execution (RCE): a request from elsewhere makes the server run a command.</p><p>The command runs with the PHP worker’s permissions. If that account can read private files or change data, the attacker may be able to do the same. In the published PHP2Shell chain, PHP reaches the vulnerable path while preparing the request, before the website’s own code runs.</p><h3>How the researchers found it</h3><p>Ryan Austin at Calif began with an old question. PHP had a history of trouble when a memory limit interrupted native code halfway through an operation. Could a similar mistake still be hiding in the runtime? During an audit that began on 30 July 2026, he pursued that idea, found several paths, and reported remote code execution to PHP on 11 August. <a href="https://calif.io/php2shell/">His account</a> traces the search.</p><p>The <a href="https://thephp.foundation/blog/2026/10/21/todays-php-security-release-and-how-were-strengthening-php-security/">PHP Foundation’s timeline</a> says OpenAI independently reported the same root cause. <a href="https://www.wiz.io/blog/php2shell-php-rce">Wiz</a> later reported another route and confirmed command execution against WordPress and Drupal test systems. Those teams established the vulnerability and its impact. The <a href="https://github.com/3em0/php2shell">3em0 repository</a> used later is a public reproduction. Its credits name @9bie for the exploit proof of concept it builds on.</p><h3>How common is PHP?</h3><p>PHP is everywhere in web hosting. In its 27 October 2026 survey, <a href="https://w3techs.com/technologies/details/pl-php">W3Techs counted PHP on 69.2%</a> of sites whose server-side language it could identify. WordPress, which uses PHP, appeared on 39.6% of all sites in that survey.</p><figure><img alt="W3Techs usage figures: PHP 69.2% of sites with a known server-side language; WordPress 39.6% of all surveyed sites, 27 October 2026." src="https://cdn-images-1.medium.com/max/1024/1*H4qCjD-qPWofku74ovJ8iA.png" /><figcaption>W3Techs usage survey, 27 October 2026.</figcaption></figure><h3>What AI agents changed</h3><p>Ryan began with a human hypothesis about an old PHP memory-limit failure, then used an AI model to look for requests that might push PHP into a similar state. One useful lead involved a request that could deliver more data than PHP’s early size check suggested. The model helped explore variants; Ryan chose the question, built the proof, and reported the result.</p><p>Wiz describes an independent search with agents that shortened the cycle of proposing a trigger, running it, and checking the result. The PHP Foundation says AI-assisted reports now arrive in much greater volume, while engineers still make the patch decisions. The search can move faster; proving, triaging, and fixing still take careful human work.</p><h3>Five ideas behind PHP2Shell</h3><ul><li><strong>Addresses and pointers.</strong> An address identifies a location in memory. A pointer stores an address.</li><li><strong>Heap memory. </strong>PHP’s session state here lives on the heap. Its storage can be reused after the request ends.</li><li><strong>Out-of-memory (OOM) failure. </strong>PHP hits its per-request memory_limit while parsing a request. The early exit can skip cleanup that would clear saved pointers.</li><li><strong>A stale pointer.</strong> A worker keeps an address after the object there is gone. A later request can put different bytes at that address.</li><li><strong>A leak and a redirected call.</strong> Response headers expose memory addresses. Forged data then makes PHP call a function that runs a command.</li></ul><p>We will build these ideas with small C++ programs, then connect them in a toy HTTP server. After that, we will return to the published 3em0 chain against PHP itself. Start with a short C++ crash course.</p><h3>Part 1: From C++ basics to a toy server</h3><h4>C++ crash course</h4><p>We will use C++ to make addresses visible. Start with these basics; the remaining syntax is explained beside the example that uses it.</p><ul><li>int a = 32; creates an integer named a. Inside a function, it is a local variable.</li><li>int* p = &amp;a; makes p store a’s address. &amp; means “address of.” *p follows that address. int** pp = &amp;p; stores the address of a pointer; **pp follows both links.</li><li>main() is where the program starts. void visit(int input) declares a function that returns no value. #include &lt;iostream&gt; makes std::cout available for terminal output.</li><li>struct Session { int id; }; groups named fields into one object. Use session.id for an object; use ptr-&gt;id when ptr points to it. The arrow means “follow the pointer, then choose the field.”</li><li>char* is a pointer to a character. A C-style string is characters followed by a zero byte that marks the end of the string. const char* points to characters the function promises not to change.</li><li>std::printf(&quot;%d %p&quot;, a, static_cast&lt;void*&gt;(&amp;a)); prints an integer with %d and an address with %p. %p expects void*, a pointer without a specific object type. static_cast&lt;T&gt;(value) converts to the type inside &lt;&gt;; it does not follow the address. p is the address stored in a pointer, while &amp;p is the pointer variable’s own address.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ad2f7534b0d012e446473b23e860a22/href">https://medium.com/media/3ad2f7534b0d012e446473b23e860a22/href</a></iframe><p>Open the <a href="https://gist.github.com/mahadirz/91b4249e1dcf16fe5df684ecdd979980">Gist</a>, click Raw, and copy its contents into pointer-chain.cpp. Then run:</p><pre>c++ -std=c++17 -O0 pointer-chain.cpp -o pointer-chain<br>./pointer-chain</pre><figure><img alt="Terminal run of pointer-chain.cpp: a at 0x16b36eb7c holds 32, p stores a’s address, pp stores p’s address, and changing **pp changes a to 33." src="https://cdn-images-1.medium.com/max/1024/1*zpx_Q7tefvwsWtRBPRNEMw.png" /><figcaption>Output from one run of pointer-chain.cpp. The diagram below uses these addresses.</figcaption></figure><figure><img alt="Three stack variables from one run: a at 0x16b36eb7c stores 32; p at 0x16b36eb70 stores a’s address; pp at 0x16b36eb68 stores p’s address. Blue and green arrows show p to a and pp to p." src="https://cdn-images-1.medium.com/max/1024/1*p75IwKQQAUtrwsFljJio7g.png" /><figcaption>Each stored pointer value matches the address of the variable it points to.</figcaption></figure><p>Match the numbers: p stores 0x16b36eb7c, the address of a. pp stores 0x16b36eb70, the address of p. *p follows one arrow; **pp follows both. Each reads 32.</p><p>After **pp = 33, a changes to 33. The addresses in p and pp stay the same. A pointer remembers a location; it does not keep an object at that location alive.</p><h4>Memory</h4><p>Think of memory as numbered byte locations. An address identifies one of those locations. A running process uses <a href="https://computationstructures.org/lectures/vm/vm.html">virtual addresses</a>, its own map for code and data. Read the diagram from bottom to top: code, static data, heap, open space, stack. The labels tell us how the process uses those addresses. They are not separate physical chips.</p><figure><img alt="A simplified vertical map of one process: high addresses and stack at top, open space, heap, static data, then code near lower addresses. Arrows show stack growth down and possible heap growth up." src="https://cdn-images-1.medium.com/max/1024/1*2-tor_YU9WfrgFA4cKwihg.png" /><figcaption>One process’s virtual address space, simplified: code and static data below, heap and stack above.</figcaption></figure><h4>Address</h4><p>The 0x prefix means the address is written in hexadecimal, a compact way to write large numbers. The number identifies the first byte occupied by a in this run’s virtual address space; the int also uses neighboring bytes. Another run may place a elsewhere. The useful fact is the match between &amp;a and the number stored in p.</p><h4>Stack</h4><p>In the diagram, the stack holds active function calls. Each call has a stack frame.</p><p>That frame provides room for local work. The visit function below creates a local variable, then returns. Call it twice and you may see the same address reused. The first local is already gone when the second one appears.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e47a72487c4db6e5790c6b8bc2d9bc2c/href">https://medium.com/media/e47a72487c4db6e5790c6b8bc2d9bc2c/href</a></iframe><p>Save the <a href="https://gist.github.com/mahadirz/39330e3321aa87bd5e35b2aba2cbd791">Gist</a> as stack.cpp, then run:</p><pre>c++ -std=c++17 -O0 stack.cpp -o stack<br>./stack</pre><h4>Heap</h4><p>These are three separate cases. int pointer = 99; creates an ordinary integer holding 99; its name does not make it a pointer. int a = 99; int* pointer = &amp;a; makes pointer hold the address of the existing local a. *pointer reads 99, and there is nothing to delete. The Gist uses int* pointer = new int(99); instead. Here new int(99) creates a separate integer on the heap, initializes it to 99, and returns its address. The pointer stores that address, and delete pointer releases the heap integer.</p><p>Here both a and pointer are local variables in the stack frame. pointer stores a’s stack address. In the new example, pointer is still local, but the integer it points to is on the heap.</p><p>Read the two print calls separately. static_cast&lt;void*&gt;(pointer) prints the address stored inside pointer, which is the heap integer’s address. static_cast&lt;void*&gt;(&amp;pointer) first uses &amp; to get the pointer variable’s own address, then converts it for printing. The cast does the same job in both expressions; the &amp; is why they print different addresses.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc68976b456d67674a702b17701d1d67/href">https://medium.com/media/dc68976b456d67674a702b17701d1d67/href</a></iframe><p>Save the <a href="https://gist.github.com/mahadirz/e79ae2be054cb031e847b0a873132127">Gist</a> as heap.cpp, then run:</p><pre>c++ -std=c++17 -O0 heap.cpp -o heap<br>./heap</pre><figure><img alt="Terminal output from stack.cpp shows two calls reusing one local address; heap.cpp shows a pointer variable and its heap integer at different addresses." src="https://cdn-images-1.medium.com/max/1024/1*VA9Yk8uGw00b_6MdNQBfCw.png" /><figcaption>Two local runs. The stack address is reused across calls; the heap value has a different address from its pointer variable.</figcaption></figure><h4>How a function pointer chooses what runs</h4><p>The heap example saved an address of data. A function pointer saves an address of code. Calling it runs the function at that address.</p><p>The program first stores normal, which prints a message. It then stores execute, which runs id. The call stays the same; the address stored in on_finish changes.</p><p>In the Gist, Handler names a function-pointer type. The function accepts text (const char*) and returns nothing (void). on_finish is a variable of that type.</p><p><a href="https://gist.github.com/mahadirz/b44f572cddffdf1504b8e2384c088696">Run the callback example on Gist (callback.cpp)</a>. Save the file, then run</p><pre>c++ -std=c++17 callback.cpp -o callback<br>./callback</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be683a14b2200969de20163c5276101b/href">https://medium.com/media/be683a14b2200969de20163c5276101b/href</a></iframe><figure><img alt="Styled terminal output: callback.cpp prints Normal handler ran, then the id command reports a local user account. The account name is masked." src="https://cdn-images-1.medium.com/max/1024/1*nc8UgJCn8DvNWAKaLVr8fw.png" /><figcaption>Typeset from a local run. The account name is masked and the group list shortened.</figcaption></figure><p>With on_finish set to normal, the call prints a message. Point it to execute, and the same call runs id. In this toy program, the code changes the pointer on purpose.</p><h4>Following pointers from data to code</h4><p>The callback example gave us a code address. To see how a heap object can lead to it, first track an ordinary data pointer. In memory-tour.cpp, pointer starts with a local integer’s address, then changes to a heap integer’s address. &amp;pointer is the pointer variable’s own address; it stays the same through both steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4159b14020a080693a49119b378f4b22/href">https://medium.com/media/4159b14020a080693a49119b378f4b22/href</a></iframe><p>Save the <a href="https://gist.github.com/mahadirz/59651fb25fe3f1559bb134ed5ff58ed0">Gist</a> as memory-tour.cpp, then run:</p><pre>c++ -std=c++17 -O0 memory-tour.cpp -o memory-tour<br>./memory-tour</pre><figure><img alt="Terminal output of memory-tour.cpp: the pointer first holds the stack value’s address and reads 42, then holds the heap value’s address and reads 99." src="https://cdn-images-1.medium.com/max/1024/1*OfZvRj_JyK7-5lhBZkjBqQ.png" /><figcaption>Typeset terminal output from a local run. Addresses change between runs.</figcaption></figure><p>At first, pointer stores &amp;stack_number, so its stored address matches stack_number’s address. &amp;pointer is different: it is the address of the pointer variable itself.</p><p>When pointer = heap_number runs, the pointer variable stays in the same place, but its stored address changes to the heap int. *pointer now reads 99. delete ends that int’s lifetime, and pointer = nullptr clears the old address in this example.</p><p>Now imagine a toy Session record at heap address 0xA120. A worker pointer stores 0xA120. The record contains another address, a callback at 0x5000 that leads to a function in code. One hop reaches the record; the second chooses a function. The diagram traces both hops.</p><figure><img alt="Three connected boxes: a global worker pointer stores heap address 0xA120; the toy Session at that address stores callback address 0x5000; code at 0x5000 is the normal handler." src="https://cdn-images-1.medium.com/max/1024/1*DST8JDnAn6foOwdy2-0MJA.png" /><figcaption>In the conceptual model, a worker pointer reaches a heap record, then the record’s callback reaches code.</figcaption></figure><h4>When a pointer outlives its object</h4><p>Give the toy record a lifetime. Request A creates a Session at 0xA120, and the worker pointer keeps that address. When cleanup ends the Session, its memory can be reused. The pointer does not clear itself; it still contains 0xA120. Our C++ Session stands in for PHP’s internal session state.</p><p>If request B places new bytes at 0xA120, following the stale pointer reads those bytes as though the old Session were still there. That is a <strong>use-after-free.</strong> A crash is one possible result. If the new bytes are shaped like fields the program trusts, the stale read can also change what the program does.</p><figure><img alt="Three stages at heap address 0xA120: a live Session, a freed slot while a stale pointer still stores 0xA120, and replacement request bytes in the same slot." src="https://cdn-images-1.medium.com/max/1024/1*67h2d7Cvn5KrDXiu4Grm8Q.png" /><figcaption>The same address at three moments: a live Session, a freed slot, and bytes owned by a later request.</figcaption></figure><p><a href="https://gist.github.com/mahadirz/11e63b0c620a6548235127ba592fcb5a">Run the tiny use-after-free example on Gist (stale-pointer.cpp)</a>. Save it, then run</p><pre>c++ -std=c++17 -O0 -fno-strict-aliasing stale-pointer.cpp -o stale-pointer<br>./stale-pointer</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79f88569e1bda3931524d5945942ce5d/href">https://medium.com/media/79f88569e1bda3931524d5945942ce5d/href</a></iframe><p>Placement new (slot) constructs a Session in bytes that already exist. alignas(Session) gives the slot suitable alignment, and sizeof(Session) reserves enough bytes. auto* lets the compiler infer a pointer’s type; it does not allocate storage. Session *stale = session copies the address without making a second Session. session-&gt;~Session() explicitly ends the object’s lifetime—the ~ names its destructor—but stale still holds that address.</p><p>The replacement object then takes the same slot. Its first three bytes are i, d, and a zero byte that ends the command string. offsetof(Session, on_finish) asks the compiler where a Session would expect its callback; the program copies the address of execute into those bytes. The last line follows stale, reads that callback, and calls it. This is deliberately undefined C++ behavior, so the example shows the failure mode without promising that every compiler or machine will print the same result.</p><figure><img alt="Terminal output from the C++ stale-pointer example. The slot, Session, stale pointer, and Replacement all show address 0x10065c000. The normal handler runs, the Session lifetime ends, the Replacement takes the same address, and the stale callback runs id. The account name is masked." src="https://cdn-images-1.medium.com/max/1024/1*qFYc8wlvUNWZvaqs_UdVrA.png" /><figcaption>Local run of stale-pointer.cpp. All five address lines match; the account name is masked. Addresses change between runs.</figcaption></figure><p>The repeated address is the point: the old Session is gone, but stale still leads to those bytes after Replacement takes the slot. The final call reads the forged callback and runs id. PHP’s allocator does not promise that reuse; the public exploit first gathers the addresses it needs.</p><h4>When a request runs out of memory</h4><p>The last example destroyed a Session, reused its slot, and called through the old pointer. We arranged that reuse by hand. PHP2Shell needs another event first: an allocation fails while PHP is preparing a request. The failure interrupts the usual path that would clear session state.</p><p>This shorter C++ program puts two request functions in one process. They are called one after the other, like two requests handled by the same worker. It does not open a network connection or run a command yet. Its job is to show exactly what survives between requests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f28eddd863a85117f19ef7a2d1ff075/href">https://medium.com/media/9f28eddd863a85117f19ef7a2d1ff075/href</a></iframe><pre>c++ -std=c++17 -O0 -Wall -Wextra oom-bridge.cpp -o oom-bridge<br>./oom-bridge</pre><p>Source: <a href="https://gist.github.com/mahadirz/866a893de865ab557a185bd8dd2baefc">oom-bridge.cpp on Gist</a>. Click Raw to copy the file.</p><p>In upload_request(), new (slot) builds a Session in the same raw storage used earlier. saved copies its address. The throw std::bad_alloc{} line deliberately simulates PHP reaching memory_limit; it is not a real C++ allocation failure. The catch ends the Session, while the normal saved = nullptr line is skipped.</p><p>next_request() builds a Replacement in that slot. The three printed addresses match: the old Session address, the new object address, and the address still stored in saved. The program does not follow saved. It has shown the lifetime mistake without invoking undefined behavior or executing a command.</p><figure><img alt="Terminal run of oom-bridge.cpp. Request A creates Session at 0x1003c8000, a simulated allocation failure ends it, and request B creates Replacement at the same address. The worker’s saved pointer still holds that address." src="https://cdn-images-1.medium.com/max/1024/1*EbWfl9M9C6mCL0rSwY6KSg.png" /><figcaption>Typeset from a local run. Request A, request B, and saved show the same address; the allocation failure is simulated.</figcaption></figure><h4>How does the script find the right address?</h4><p>A function has an address in memory, just as an object does. The next problem is finding it. Modern systems move program code to a different address each time it starts. This protection is called address-space layout randomization, or ASLR. A number that worked in one run may point nowhere useful in the next.</p><p>A leak can give us a starting point. Suppose the address of one function appears in a response as 0x5000. In the same build, the function we want is 0x5c bytes after it. We add those numbers and get 0x505c. The actual addresses may move next time, but the distance between those two functions in that exact build stays the same.</p><p>The next program uses the two function names from the final toy: safe_handler and run_shell. Both functions are empty here. It prints their addresses, subtracts them to get an offset, then adds the offset to the first address.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebcab95fbae1bbc29f4b6b9f11ece74a/href">https://medium.com/media/ebcab95fbae1bbc29f4b6b9f11ece74a/href</a></iframe><p>Save <a href="https://gist.github.com/mahadirz/fc337296f4c9d6ca7d3ec83004f0a31a">the Gist as address-offset.cpp</a>, then run it twice:</p><pre>c++ -std=c++17 -O0 address-offset.cpp -o address-offset<br>./address-offset<br>./address-offset</pre><p>Run the program twice. The absolute addresses may move between runs, but the offset between these two functions in the same build stays the same. The calculated address should match run_shell in each run. reinterpret_cast&lt;std::intptr_t&gt; turns a function address into an integer so the program can subtract and add it; std::hex and std::dec only change how the number is printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IEo9wgtUKk5Kcj9bMYeeQ.png" /><figcaption>Typeset from two local runs. The function addresses move; their offset remains four bytes.</figcaption></figure><p>Printing both addresses in one process demonstrates the arithmetic. The final Python client has to get its information from two different places:</p><ul><li>delta comes from the exact local server binary. The nm tool lists the binary’s symbols, including the locations of safe_handler and run_shell. Subtracting them gives the distance between the functions.</li><li>safe_address comes from a cookie sent by the running server. It gives the current address of safe_handler after ASLR.</li><li>target is that leaked address plus the distance. It is the calculated address of run_shell in this server process.</li></ul><p>The <a href="https://gist.github.com/mahadirz/2d388d8adac87eef7f305fc3352b5d89#file-exploit-py-L62">final client</a> performs this calculation:</p><pre>delta = (<br>    symbol_address(args.binary, &quot;run_shell&quot;)<br>    - symbol_address(args.binary, &quot;safe_handler&quot;)<br>)<br>target = safe_address + delta</pre><p>symbol_address() runs nm on the binary file; it does not inspect the running server. Having the exact server binary is a deliberate assumption in this lab. The four-byte offset in the small example belongs to that small program. The client measures a new offset from the server binary, even though the function names are the same.</p><h4>From a calculated address to replacement bytes</h4><p>Now connect target to the stale-pointer example. In the final server, safe_handler plays the role of normal, run_shell plays the role of execute, and the callback field is named handler instead of on_finish. The OOM example’s saved pointer is named stale here.</p><p>The integer-only Session from the OOM example grows into a record with a command buffer and a callback:</p><pre>struct Session {<br>    char command[96];<br>    Handler handler;<br>};</pre><p>Handler names a function-pointer type. In this server, the function accepts the command and a reference to an output string, then returns nothing. The function fills that string so the HTTP server can send the result back to the client.</p><p>On the toy’s intended 64-bit little-endian platform, the command occupies bytes 0–95, and the handler occupies bytes 96–103. The Python client constructs replacement bytes in the same order:</p><pre>forged = command.ljust(96, b&quot;\0&quot;) + struct.pack(&quot;&lt;Q&quot;, target)</pre><p>ljust pads the command with zero bytes until that part is 96 bytes long. The first zero ends the C-style command string. struct.pack(&quot;&lt;Q&quot;, target) represents the calculated address as eight bytes in little-endian order: the least significant byte goes first.</p><pre>Bytes 0–95:    command + zero padding<br>Bytes 96–103: calculated run_shell address</pre><p>/reclaim copies these 104 bytes into the old slot. stale still holds that slot’s address. When /finish runs the following line, it treats the replacement bytes as the old Session:</p><pre>stale-&gt;handler(stale-&gt;command, output);</pre><p>The command field now supplies id, and the handler field supplies the address of run_shell. The stale pointer connects the replacement data to the function call. The HTTP requests below separate those events so we can watch each step.</p><h4>Putting the toy model on HTTP</h4><p>So far, both “requests” were function calls inside one process. The next toy puts an HTTP boundary between the same events: a simulated allocation failure ends a Session, a saved pointer survives, and a later request replaces the bytes in its slot. A Python client sends requests to a C++ server on 127.0.0.1 and eventually receives the server’s id output.</p><p>The earlier examples each supply one part of this server. The pointer examples showed how an address can survive its object. The OOM example showed how cleanup can miss the step that clears it. The callback example showed how bytes in a reused slot can choose a function. The address example showed how a leaked function address and a fixed offset can locate another function after ASLR moves the code. The four requests below put those events in order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ni_YnQe0ReTrJDvExY8_jQ.png" /><figcaption>The toy combines a reusable memory slot with a code address calculated from a leak. /reclaim brings the two paths together; the slot models heap reuse.</figcaption></figure><p>The server file is longer because it includes socket setup and HTTP parsing. Focus on four branches in handle():</p><ul><li><strong>POST </strong><strong>/upload</strong> ends the Session during a simulated allocation failure. Afterward, active is null, but stale still holds the old slot’s address.</li><li><strong>GET </strong><strong>/leak</strong> exposes the old slot address and the original safe_handler address in a cookie. The client now has the runtime code address needed for its calculation. This toy exposes addresses directly; PHP’s real chain gets them through reads beyond the intended heap area.</li><li><strong>POST </strong><strong>/reclaim</strong> copies the client’s command and calculated handler address into the released slot. Afterward, the slot holds replacement bytes, while stale still holds the same address.</li><li><strong>GET </strong><strong>/finish</strong> follows stale and interprets those bytes as a Session. Its handler call reaches run_shell, which runs id and collects the output for the HTTP response.</li></ul><p>There are four HTTP requests and five numbered stages in the client’s output. Stage 3 — the address calculation — happens locally between /leak and /reclaim; it sends no request. By then the client knows which function address to put in the replacement bytes.</p><p>The one-slot arena guarantees that /reclaim reuses the old address, so the client prints the slot address but does not calculate with it. Although the client labels it heap, the C++ slot is an array inside the global arena object. It has static storage duration: it remains allocated for the process’s lifetime. Placement new constructs objects there without allocating heap storage. This reusable slot models PHP’s heap reuse; PHP’s real allocator gives no such guarantee, which is why its heap leak matters.</p><p>The complete server.cpp, exploit.py, and build.sh are in <a href="https://gist.github.com/mahadirz/2d388d8adac87eef7f305fc3352b5d89">this Gist</a>. Save all three files in one folder. The server deliberately simulates an allocation failure when an upload exceeds a small byte limit. The later stale read deliberately invokes undefined C++ behavior, just as the earlier stale-pointer example did; the controlled slot makes the intended failure mode easier to observe.</p><p>In the first terminal, build and start the server:</p><pre>sh build.sh<br>./server --port 18092</pre><p>In a second terminal, send the requests:</p><pre>python3 exploit.py --port 18092</pre><p>In the terminal image, the simulated upload failure returns HTTP 500. The next response exposes a slot address (printed as heap) and a code address in a cookie. The client calculates target, fills the slot with the replacement bytes, and calls /finish. The response then contains the server’s id output.</p><figure><img alt="Terminal output from a local C++ server and Python client: upload returns HTTP 500, the client leaks heap and code addresses, reclaims the freed slot, calls the stale handler, and receives uid=501(local-user) from id." src="https://cdn-images-1.medium.com/max/1024/1*DU32FhmFVW6vxgauG3Q1GA.png" /><figcaption>A local run of the C++ server and Python client. The client receives the server’s id output after the stale handler call; the account name is masked.</figcaption></figure><p>Stop the server with Ctrl+C, then restart it with the fix enabled:</p><pre>./server --fixed --port 18093</pre><p>Run the same client in the second terminal:</p><pre>python3 exploit.py --port 18093</pre><p>This time GET /leak returns HTTP 410, “No stale session,” and the client stops before it can reclaim the slot or call the handler. In fixed mode the server does not retain the Session pointer after freeing the object. The later request has no old address to follow.</p><p>The toy server makes memory reuse predictable. The published PHP test below has to arrange reuse through PHP’s allocator and its internal structures.</p><h3>Part 2: The real PHP2Shell chain</h3><p>The toy has now shown the complete chain: an allocation failure leaves an old pointer, a leak helps locate code, and replacement bytes change a later call. To map that model onto PHP, first look at where the upload is handled and how state survives between requests.</p><p>PHP2Shell needs two address clues. Reads beyond the intended memory area expose stray bytes in Set-Cookie response headers. A Set-Cookie header normally tells a browser what cookie to keep; here it also exposes memory. One leak locates temporary data on the heap. Another locates libphp.so, the PHP code loaded into Apache. Together, they help the script locate its data and the code it targets.</p><h4>Why does an upload reach PHP before the page?</h4><p>PHP’s <a href="https://www.php.net/manual/en/session.upload-progress.php">session upload progress feature</a> watches an upload when the request includes a special form field. A multipart request is the usual HTTP format for sending a file and other form fields together. PHP reads that request before the page code runs. In the published example, the page only prints OK; it has no upload form and does not call session_start().</p><p>This explains the surprising part of the attack surface: a request can trigger a vulnerable path in the runtime even if the application’s own code looks harmless. The <a href="https://github.com/3em0/php2shell">3em0 repository</a> includes the request sequence and a small server setup used to reproduce this behavior.</p><figure><img alt="An HTTP multipart request with a progress field and file reaches an Apache worker. PHP parses the upload and records the byte count in session data before index.php prints OK. The vulnerable work occurs during PHP parsing." src="https://cdn-images-1.medium.com/max/1024/1*rkAsIreCC4iG3p4xMTqYpg.png" /><figcaption>PHP tracks upload progress while parsing the request, before index.php prints OK.</figcaption></figure><h4>What happened when PHP ran out of memory?</h4><p>PHP’s <a href="https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w">out-of-memory advisory</a> describes what happens when PHP runs out of memory while handling a request. In the affected versions, PHP could leave an operation before all of its temporary state was ready for cleanup. Later cleanup code would then encounter a state it did not expect. The upload parser gave the test program a way to exhaust memory at a useful moment.</p><p>Here “out of memory” means a PHP request hits its configured memory_limit. It does not require the machine to run out of RAM. The published requests send multipart data that makes PHP allocate memory while it initializes session upload progress, before index.php starts. A fatal allocation failure at the chosen point interrupts normal cleanup.</p><p>The 3em0 chain uses this interruption twice. During the first leak, a failed allocation can leave the session ID pointer, PS(id), stale. A later request makes PHP treat reused heap bytes as a string; the Set-Cookie header then reads past the intended heap area and exposes an address. For the final command call, another failure leaves the session variables pointer, PS(http_session_vars), stale. Those are two different pointers. Neither stage is a stack overflow.</p><p>The companion <a href="https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp">stale-global-state advisory</a> describes the other half. Apache reuses a worker process for more than one request. PHP had kept a pointer from an earlier request in a variable that survived into the next request on that worker. After that request freed its memory, the pointer still held the old address. A later request handled by the same worker could read whatever now occupied that space.</p><p>The later request has to reach the worker that holds the stale pointer. Apache usually has several workers, so the test program nudges them until it reaches the right one. Even then, a different PHP build or memory layout can make a leak miss. HEAP_LEAK_FAILED tells us that this stage did not work in that test; it does not settle whether the server is vulnerable.</p><p>The C++ examples built the pieces one at a time. They used a controlled memory slot and a direct address leak so we could see the mistake. Now follow the published 3em0 chain in PHP itself, where the script must arrange those steps in the runtime’s allocator:</p><ol><li>Prepare one worker. Apache has several processes ready to handle requests. The script tries to get the related requests through the same process, where the old pointer can persist.</li><li>Find temporary data in memory. One upload request leaves an old session pointer behind. A later read goes beyond the intended memory area, and bytes in a Set-Cookie header reveal where PHP placed temporary data.</li><li>Find PHP’s code. Another leaked pointer falls inside libphp.so. With it, the script can calculate where the relevant PHP functions are in this particular build.</li><li>Trigger the final stale pointer, then fill its slot. A second memory-limit failure leaves PS(http_session_vars) pointing to released heap memory. Carefully sized form fields reuse that slot with bytes shaped like a PHP reference and a HashTable, the internal structure PHP uses for arrays.</li><li>Reach a command-running function. When PHP cleans up the forged structure, it follows a function address stored there. The script aims that call at PHP’s system function (zif_system), which runs the proof command.</li></ol><p>The C++ toy changed a callback directly. PHP takes a longer route: an upload request leaves an old pointer behind, later requests fill the released memory with chosen bytes, and PHP interprets those bytes as internal objects during cleanup. The object layouts are PHP-specific, but the lifetime mistake is the same one we saw in the toy.</p><h4>Trying the published example on a test server</h4><p>The 3em0 repository includes a Docker Compose setup using PHP 8.4.26 and Apache. Its test configuration uses one prefork worker, display_errors=On, memory_limit=8M, max_input_vars=1000, session cookies on, and strict mode off. Those settings help this particular chain reach and expose the stale state. The commands below start that server and run the published script on a Linux x86–64 machine you control. By default, it runs id and writes the result to a file on the host.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbfc57192473349ed90adb0355c88a68/href">https://medium.com/media/dbfc57192473349ed90adb0355c88a68/href</a></iframe><p>Copy the full Bash script from <a href="https://gist.github.com/mahadirz/ec349388a4d4321ef582876b467c93a7">Gist</a>.</p><p>On my own Linux x86–64 machine, the script first printed an address for temporary data, then an address for PHP’s code, and finally PROOF: uid=33(www-data). I opened the output file on the host to check that result myself. The web server had run the command.</p><figure><img alt="Typeset output from the private PHP 8.4.26 Apache test server: two leaked addresses, followed by PROOF: uid=33(www-data)." src="https://cdn-images-1.medium.com/max/1024/1*ayDk9-rErQAikszjDKt9hA.png" /><figcaption>PHP 8.4.26 Apache test output, typeset from a recorded local run.</figcaption></figure><p>I also tried the script against PHP 7.0 using PHP’s built-in web server and got HEAP_LEAK_FAILED. That environment differs from the repository’s Apache setup. The current repository reports working profiles for tested PHP 8.3, 8.4, and 8.5 Apache images. On an ARM Mac running x86–64 emulation, I saw both address leaks but no final command. The tests show why a failed run is not a verdict on the underlying bug.</p><h3>What changes after the fix?</h3><p>The PHP project patched the two original advisories in 8.2.35, 8.3.36, 8.4.27, and 8.5.12. Install a fixed release (or your vendor’s patched package) and restart the web server so its workers load the new code. PHP’s <a href="https://www.php.net/archive/2026.php">23 October follow-up</a> describes a separate, unusual case that requires an application to change session.serialize_handler at runtime before starting a session. For that setup, PHP suggests setting session.upload_progress.enabled=0 until the next bugfix release. Applications that never change the serializer at runtime can keep upload progress enabled.</p><p>The page that prints OK is not where this chain begins. PHP has already parsed the upload and touched session state before index.php runs. A failed cleanup can leave an old address behind; later request bytes can occupy that address, and PHP may follow data it should no longer trust. The fix belongs in the PHP runtime and in the version the web server actually loads.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d85731d84944" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configure Claude Desktop with Mythos (DeepSeek V4 alias)]]></title>
            <link>https://medium.com/@mahadir.ahmad/configure-claude-desktop-with-mythos-deepseek-v4-alias-281e3dc6d2fd?source=rss-f8a461eb6548------2</link>
            <guid isPermaLink="false">https://medium.com/p/281e3dc6d2fd</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Mahadir Ahmad]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 13:53:36 GMT</pubDate>
            <atom:updated>2026-06-05T13:53:36.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzLoQQ6B5XOUUuYmiIhEzg.png" /><figcaption>Prank my colleague with having Mythos access</figcaption></figure><p>Claude Desktop has recently introduced support for third-party model configurations, opening up a new level of flexibility for power users, developers, and AI enthusiasts. With this capability, we are no longer limited to using only the default Claude models inside Claude Desktop. Instead, we can configure Claude Desktop to route selected model names to external providers or internal model endpoints.</p><p>In this article, I will walk through how I configured Claude Desktop to work with 3rd pary model, which in this setup I use <strong>DeepSeek V4 </strong>with <strong>Mythos</strong> alias. This allows me to switch between Claude models available through my subscription and DeepSeek V4 as a more cost-effective alternative for certain workloads.</p><p>The main idea is simple: use Claude Desktop as the interface, while mapping custom model names such as <strong>Claude Mythos</strong> and <strong>Claude Mythos Flash</strong> to DeepSeek-backed models. This gives me the familiar Claude Desktop experience while unlocking much cheaper usage for tasks that do not necessarily require Claude’s native models.</p><h3>Why Use DeepSeek V4 with Claude Desktop?</h3><p>Claude is excellent, especially for reasoning, writing, coding, and complex task execution. However, depending on your subscription tier and usage pattern, you may eventually run into usage limits. For users who work with large volumes of tokens, those limits can become a bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*kse2hJNUVHACgh8Mpqy9Vg.png" /></figure><p>This is where DeepSeek becomes interesting.</p><p>DeepSeek offers highly competitive API pricing while delivering performance that, for many day-to-day tasks, is close enough to Claude to be genuinely useful. I have been using DeepSeek for specific categories of work such as drafting, summarization, coding assistance, brainstorming, and bulk text processing.</p><p>In my own experiment, I have processed more than <strong>136 million tokens in a single day</strong>, and the total cost was less than <strong>$1.50</strong>. That level of affordability makes DeepSeek a very practical option when you need high-volume AI usage without burning through your Claude subscription quota.</p><p>To be clear, I am not suggesting that DeepSeek replaces Claude completely. Claude still has its strengths, especially for certain reasoning-heavy or high-context tasks. But for many practical workflows, having DeepSeek available inside Claude Desktop gives you the best of both worlds: Claude when you need it, and a cheaper alternative when scale matters.</p><h3>What This Setup Does</h3><p>This setup launches Claude Desktop with a third-party profile and maps selected model names to DeepSeek models.</p><p>For example:</p><ul><li>Claude Mythos Flash is mapped to deepseek-v4-flash</li><li>Claude Mythos is mapped to deepseek-v4-pro</li></ul><p>Once configured, you can use these custom model aliases inside Claude Desktop and route requests to DeepSeek through the launcher.</p><p>The result is a more flexible Claude Desktop environment where you can switch between your subscription-based Claude models and your configured DeepSeek aliases.</p><h3>Step-by-Step Guide</h3><h3>1. Clone the Launcher Repository</h3><p>First, clone the launcher from my <a href="https://github.com/mahadirz/claude-desktop-deepseek-launcher">GitHub</a> repository.</p><pre>git clone https://github.com/mahadirz/claude-desktop-deepseek-launcher .</pre><p>This repository contains the launcher script needed to start Claude Desktop with the third-party profile and model mappings.</p><p>Make sure you are cloning it into the directory where you want to run the launcher. The . at the end of the command means the repository will be cloned into the current directory.</p><h3>2. Get Your DeepSeek API Key</h3><p>Next, you will need an API key from <a href="https://platform.deepseek.com/api_keys">DeepSeek</a>.</p><p>Go to the DeepSeek platform, create or log in to your account, and generate an API key. Keep this key secure, because it will be used by the launcher to authenticate your requests.</p><p>Your API key will usually look something like this:</p><pre>sk-xxx</pre><p>Do not share your real API key publicly, commit it into GitHub, or paste it into screenshots.</p><h3>3. Launch Claude Desktop with the Third-Party Profile</h3><p>Once you have your DeepSeek API key, you can launch Claude Desktop using the provided Python script.</p><p>Run the following command:</p><pre>python3 launch_claude_desktop_deepseek.py \<br>  --api-key &quot;sk-xxx&quot; \<br>  --model-map &quot;Claude Mythos Flash=deepseek-v4-flash&quot; \<br>  --model-map &quot;Claude Mythos=deepseek-v4-pro&quot; \<br>  --yes</pre><p>Replace &quot;sk-xxx&quot; with your actual DeepSeek API key.</p><p>The --model-map arguments define how Claude Desktop should map the visible model names to the underlying DeepSeek models.</p><p>In this example:</p><pre>--model-map &quot;Claude Mythos Flash=deepseek-v4-flash&quot;</pre><p>maps the name <strong>Claude Mythos Flash</strong> to the DeepSeek flash model.</p><p>And:</p><pre>--model-map &quot;Claude Mythos=deepseek-v4-pro&quot;</pre><p>maps the name <strong>Claude Mythos</strong> to the DeepSeek pro model.</p><p>The --yes flag is used to automatically confirm the launcher’s setup prompts.</p><p>After launching Claude Desktop with this configuration, you should be able to use the mapped Mythos models from within the Claude Desktop environment.</p><h3>Optional: Add Chrome DevTools MCP</h3><p>If your workflow involves browser automation, website inspection, or controlling Chrome through Claude Desktop, you can optionally add the Chrome DevTools MCP server.</p><p>This is useful if you want Claude Desktop to interact with a browser, inspect web pages, debug frontend issues, or assist with browser-based workflows.</p><p>To configure it, open Claude Desktop and go to:</p><pre>Settings -&gt; Developer -&gt; Edit Config</pre><p>Then add the following MCP configuration:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;chrome-devtools&quot;: {<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [&quot;-y&quot;, &quot;chrome-devtools-mcp@latest&quot;]<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNFSRg8C3zkweg3z9iXGLw.png" /></figure><p>After saving the configuration, restart Claude Desktop so the MCP server can be loaded properly.</p><p>Once enabled, Claude Desktop should be able to use the Chrome DevTools MCP server whenever browser control or inspection is needed.</p><h3>4. Restore back to official Claude Model</h3><pre>python3 launch_claude_desktop_deepseek.py --restore --yes</pre><h3>Example Use Cases</h3><p>This setup is especially useful for workloads where cost matters more than using the absolute strongest model available.</p><p>Some examples include:</p><ul><li>Processing large documents</li><li>Summarizing long text</li><li>Rewriting or polishing drafts</li><li>Generating boilerplate code</li><li>Creating test cases</li><li>Brainstorming article outlines</li><li>Performing bulk text transformations</li><li>Running repetitive coding or documentation tasks</li></ul><p>For these kinds of tasks, DeepSeek can be a very cost-effective backend while Claude Desktop remains the main user interface.</p><p>I personally like this workflow because it lets me reserve Claude usage for tasks where I really want Claude’s native strengths, while offloading cheaper and higher-volume tasks to DeepSeek.</p><h3>Notes and Considerations</h3><p>There are a few things worth keeping in mind.</p><p>First, model behavior will not be identical to Claude. Even though the model names appear inside Claude Desktop, the actual responses are generated by DeepSeek when using the mapped Mythos aliases. This means writing style, reasoning behavior, tool usage, and formatting may differ from native Claude models.</p><p>Second, pricing and performance can change over time. Always check the latest DeepSeek API pricing and model availability before relying on this setup for production usage.</p><p>Third, keep your API key secure. If you are running this locally, avoid hardcoding your key into scripts or committing it to a repository. Use environment variables or a local secrets file where possible.</p><p>Finally, this setup is best treated as a power-user workflow. If you are comfortable with Python scripts, command-line tools, API keys, and Claude Desktop developer settings, it is straightforward. If not, take your time and understand what each step does before running it.</p><h3>Final Thoughts</h3><p>Claude Desktop’s support for third-party profiles makes it much more flexible than before. By mapping custom model aliases to DeepSeek V4, we can create a hybrid workflow that combines the polished Claude Desktop experience with the affordability of DeepSeek’s API.</p><p>For me, this setup has been especially useful because I can continue using Claude for high-value reasoning and writing tasks, while relying on DeepSeek for high-volume workloads where cost efficiency is more important.</p><p>With over 136 million tokens processed at a cost of less than $1.50, this workflow has proven to be a practical and affordable way to extend AI usage beyond normal subscription limits.</p><p>If you regularly work with large amounts of text, code, or documentation, configuring Claude Desktop with a DeepSeek-backed Mythos profile is definitely worth exploring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281e3dc6d2fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customising Airbyte Connector for Xero]]></title>
            <link>https://medium.com/@mahadir.ahmad/customising-airbyte-connector-for-xero-792ecee0ab43?source=rss-f8a461eb6548------2</link>
            <guid isPermaLink="false">https://medium.com/p/792ecee0ab43</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[airbyte]]></category>
            <dc:creator><![CDATA[Mahadir Ahmad]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 11:59:47 GMT</pubDate>
            <atom:updated>2026-01-18T11:59:47.201Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m writing this as note to myself for the future and for anyone else who may find it useful, recently I’ve been exploring Airbyte for work, my intention is to replace custom API application for data replication that require in house code to extract and load the data into a Data Lake. This would reduce the workload of Data Engineers and allow us to focus more on higher level tasks.</p><blockquote>In <a href="https://www.amazon.com/Staff-Engineer-Leadership-beyond-management-ebook/dp/B08RMSHYGG"><em>Staff Engineer: Leadership Beyond the Management Track</em></a>, Will Larson highlights that staff engineers should prioritize work that creates leverage across the organization, focusing on shared platforms and high-impact strategy rather than repeatedly solving the same problems in isolation.</blockquote><p>I’ve found many of the sources and destinations provided by Airbyte with over 600 connectors available out of the box meet many of the existing and potentially future needs. The connectors also can be extended if required providing a unified interface and scalable infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7OHk7QH6UmXE2YJfJjl7w.png" /><figcaption>Illustration of Airbyte as orchestrator</figcaption></figure><p>My first project exploration with Airbyte was for Xero, <a href="https://docs.airbyte.com/integrations/sources/xero">Xero integration</a> is not an official connector provided by Airbyte, but rather available through the Marketplace.</p><p>My initial expectation was that this project should be completed within 1–3 days, however like many engineering project, I encountered major challenges that only became apparent after fully immersing myself in the work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_30Bm2e7tL1bXitgoO6SA.png" /><figcaption>Limitation of the existing Xero Connector for Credential’s option</figcaption></figure><p>The marketplace integration provides only two authentication options: <strong>OAuth Custom Connection</strong> and <strong>Bearer Access Token</strong>. However I already have an existing Xero application that uses <a href="https://developer.xero.com/documentation/guides/oauth2/auth-flow/">OAuth Code Flow</a> which I need to run this in parallel to provide legacy support for period of time. The <a href="https://developer.xero.com/documentation/guides/oauth2/custom-connections">OAuth Custom Connection</a> is only supported in limited countries and require a separate purchase. That left me with only single option: Bearer Access Token.</p><p>I then experimented with the <a href="https://developer.xero.com/documentation/guides/oauth2/pkce-flow">PKCE flow</a> as documented in the integration guide, however I soon discovered that Bearer Access Token expire after 30 minutes and the integration <strong>does not</strong> <strong>automatically</strong> renew the token. After few hours of investigation, I found that the main reason lies in the underlying configuration within the connector code itself. Furthermore, connector version after <a href="https://github.com/airbytehq/airbyte/issues/66667">2.1.0 are known to have issue</a> with data refresh, I raised a Pull Request (PR) to address this, but it may take some time before it is merged. Hence, the current workarounds are either downgrade the version back to version 2.0.1 or extend the connector ourselves.</p><p>I chose the second option primarily because</p><ul><li>I want the connector to au<strong>tomatically refresh the token</strong>, especially for sync runs that take longer than 30 minutes.</li><li>I want to retrieve the refresh_token after the sync finishes, so it can be <strong>reused</strong> by the existing application.</li><li>I want to checkpoint the load at daily granularity. This allows<strong> syncing large datasets</strong> (for example, over 500k records). With pagination, the sync requires more than 5,000 API calls.</li></ul><p>My final workflow looks something like the following diagram. Note that my current refresh approach is manual rather than scheduled, I use Airflow to schedule the refresh and coordinate it with my legacy application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyWyfAes_efD45VIfsgL6w.png" /></figure><h3>Extending The Connector</h3><p>Enough talking, let’s get into the real stuff. This guide assumed familiarity with git, docker, yaml, python and command line</p><h4>TLDR</h4><ul><li>The final modified codes are already inside <a href="https://github.com/mahadirz/airbyte">https://github.com/mahadirz/airbyte</a></li><li>If you trust my container image, feel free to use the fully built image here <a href="https://hub.docker.com/r/madetcullen/my-source-xero">https://hub.docker.com/r/madetcullen/my-source-xero</a> . You can directly add custom connector from Airbyte web console, Workspace Setting -&gt; Sources -&gt; + New Connector.</li></ul><h4>1. Clone the Git repository</h4><p>Clone the official airbyte codebase for the integration</p><pre>git clone https://github.com/airbytehq/airbyte</pre><h4>2. Inspect the content</h4><p>The Xero source configuration is located under directory <strong>airbyte-integrations/connectors/source-xero. </strong>You can inspect the content</p><pre># cd airbyte-integrations/connectors/source-xero<br># ls -lah .<br><br>drwxr-xr-x   13 madet  lotr  416B Jan 17 15:26 .<br>drwxr-xr-x  679 madet  lotr    21K Jan 10 23:46 ..<br>-rw-r--r--    1 madet  lotr   2.3K Jan 10 23:46 acceptance-test-config.yml<br>-rw-r--r--@   1 madet  lotr   480K Jan 11 01:34 catalog.json<br>-rw-r--r--@   1 madet  lotr   4.0K Jan 11 20:44 components.py<br>-rw-r--r--@   1 madet  lotr   352B Jan 11 20:35 config.json<br>-rw-r--r--@   1 madet  lotr   415B Jan 16 18:14 Dockerfile<br>-rw-r--r--    1 madet  lotr   2.3K Jan 10 23:46 icon.svg<br>drwxr-xr-x   11 madet  lotr   352B Jan 10 23:46 integration_tests<br>-rw-r--r--@   1 madet  lotr   665K Jan 17 15:26 manifest.yaml<br>-rw-r--r--    1 madet  lotr   3.1K Jan 10 23:46 metadata.yaml<br>-rw-r--r--    1 madet  lotr   3.6K Jan 10 23:46 README.md<br>drwxr-xr-x    6 madet  lotr   192B Jan 10 23:46 unit_tests</pre><h4>3. Modify Manifest</h4><p>While waiting for my PR that patched the issue with version 2.1.x to be deployed. We can also manually patch it first. You can check my PR <a href="https://github.com/airbytehq/airbyte/pull/71340/files">here</a> for the change. It’s just a single line patch for airbyte-integrations/connectors/source-xero/components.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VL6lDjAaW6MfRyBnh0x_kw.png" /></figure><p>4. Modify the manifest.yaml. This file stores the declaration of the configs and how to pull the data through the source.</p><p>Add new type of Credentials, Oauth2 Code Flow, we will need client_id, client_secret and refresh_token.</p><pre>      credentials:<br>        type: object<br>        oneOf:<br>          - type: object<br>            title: OAuth2 Code Flow<br>            required:<br>              - auth_type<br>              - client_id<br>              - refresh_token<br>              - client_secret<br>            properties:<br>              auth_type:<br>                type: string<br>                const: oauth2_code_flow<br>              client_id:<br>                type: string<br>                title: Client ID<br>              client_secret:<br>                type: string<br>                title: Client Secret<br>              refresh_token:<br>                type: string<br>                title: Refresh Token<br>              access_token:<br>                type: string<br>                airbyte_secret: true<br>                title: Access Token<br>              token_expiry_date:<br>                type: string<br>                title: Token Expiry Date</pre><p>The config will then used by base_requester which we define a new oauth2_code_flow with type OAuthAuthenticator. This OAuthAuthenticator will then use the client_id, secret and refresh_token to get the access_token to be used for the bearer authorization.</p><pre>  base_requester:<br>    type: HttpRequester<br>    url_base: https://api.xero.com/api.xro/2.0/<br>    authenticator:<br>      type: SelectiveAuthenticator<br>      authenticators:<br>        oauth2_code_flow:<br>          type: OAuthAuthenticator<br>          grant_type: refresh_token<br>          client_id: &quot;{{ config[&#39;credentials&#39;][&#39;client_id&#39;] }}&quot;<br>          client_secret: &quot;{{ config[&#39;credentials&#39;][&#39;client_secret&#39;] }}&quot;<br>          refresh_token: &quot;{{ config[&#39;credentials&#39;][&#39;refresh_token&#39;] }}&quot;<br>          token_refresh_endpoint: https://identity.xero.com/connect/token<br>          access_token_name: access_token<br>          expires_in_name: expires_in<br>          refresh_token_updater:<br>            refresh_token_name: refresh_token<br>            refresh_token_config_path:<br>              - credentials<br>              - refresh_token<br>            access_token_config_path:<br>              - credentials<br>              - access_token</pre><p>Optionally:</p><p>I also removed the Tenant ID to be masked, as I believe it’s not a secret and make my process easier to inspect for any mistake in key in the information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIgXNEYz4BpduUigI8-2NQ.png" /></figure><p>I added two new lines for bank_transactions: step: “P1D” and cursor_granularity: “PT1S”. This allow the checkpointing as described earlier. P1D is each step is 1 day and PT1S is the 1 second granularity during the step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iq9pjQPwjRelFbKRl1C--Q.png" /></figure><h4>5. Test the connector</h4><p>Create a config.json and replace the values accordingly with your own credentials</p><pre>{<br>  &quot;credentials&quot;: {<br>    &quot;auth_type&quot;: &quot;oauth2_code_flow&quot;,<br>    &quot;client_id&quot;: &quot;123&quot;,<br>    &quot;client_secret&quot;: &quot;123&quot;,<br>    &quot;refresh_token&quot;: &quot;123&quot;<br>  },<br>  &quot;tenant_id&quot;: &quot;xxxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&quot;,<br>  &quot;start_date&quot;: &quot;2026-01-01T00:00:00Z&quot;<br>}</pre><p>Discover the stream schema</p><pre>docker run --rm \<br>  -v &quot;$PWD:/data&quot; \<br>  airbyte/source-xero:2.1.4 discover \<br>--config /data/airbyte-integrations/connectors/source-xero/config.json \<br>&gt; discover_output.json</pre><p>Let’s only take invoice for testing</p><pre>cat discover_output.json | jq &#39;<br>  {<br>    streams: [<br>      {<br>        stream: .catalog.streams[] | select(.name==&quot;invoices&quot;),<br>        sync_mode: &quot;full_refresh&quot;,<br>        destination_sync_mode: &quot;append&quot;<br>      }<br>    ]<br>  }<br>&#39; &gt; catalog.json</pre><p>Run the connector for downloading the</p><pre>docker run --rm \<br>  -v &quot;$PWD:/data&quot; \<br>  airbyte/source-xero:2.1.4 read \<br> --config /data/airbyte-integrations/connectors/source-xero/config.json \<br>  --catalog /data/airbyte-integrations/connectors/source-xero/catalog.json \<br>  &gt; read_output.jsonl</pre><p>If everything works as expected the read_output.jsonl should capture no errors.</p><h4>6. Build the container image</h4><p>create Dockerfile</p><pre>FROM airbyte/source-xero:2.1.4<br><br># Copy your modified declarative files into the image<br>COPY components.py /airbyte/integration_code/source_declarative_manifest/components.py<br>COPY manifest.yaml /airbyte/integration_code/source_declarative_manifest/manifest.yaml</pre><p>Build a new image, if you need to pull this from remote machine you can push the image into your preferred Docker repository, I’m using Docker.com</p><pre>docker build -t my-source-xero:2.1.4 .<br>docker tag my-source-xero:2.1.4 {docker_account}/my-source-xero:2.1.4<br>docker push {docker_account}/my-source-xero:2.1.4</pre><h4>7. Add new Connector</h4><p>from Airbyte web console you can now add the new connector.</p><p>Workspace Setting -&gt; Sources -&gt; + New Connector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKjZFFrB0Kj7bapwpS_OKA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=792ecee0ab43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers Learn Without Training: The Hidden Mechanics of In-Context Learning — Part 1…]]></title>
            <link>https://medium.com/@mahadir.ahmad/transformers-learn-without-training-the-hidden-mechanics-of-in-context-learning-part-1-0b4a27d05985?source=rss-f8a461eb6548------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b4a27d05985</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Mahadir Ahmad]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 05:14:49 GMT</pubDate>
            <atom:updated>2025-12-16T05:14:49.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transformers Learn Without Training: The Hidden Mechanics of In-Context Learning — Part 1 (Synaptic Plasticity)</h3><p>The human brain is fascinating not only because it is capable of general intelligence, but also because of its remarkable energy efficiency. It is estimated that the brain consumes only about 15 watts to function. In contrast, a single NVIDIA H200 GPU can draw up to 700 watts of power, yet is only capable of running inference on a ~100B-parameter model. For training, it would likely require four or more such GPUs.</p><figure><img alt="Ilustration of brain vs GPU energy consumption" src="https://cdn-images-1.medium.com/max/1024/1*sYPBFpbfEc36IiSy6FnbHw.png" /></figure><p>However, comparing these systems directly may not be entirely fair. Machines can run millions of times faster than humans at specialized tasks such as mathematical computation, while humans cannot match this speed. In addition, the human brain is organic matter that relies on chemical reactions layered on top of electrical signaling, so measuring power consumption in watts is not an equal comparison. What remains fascinating, however, is the brain’s ability to rewire itself without explicit instruction. Current AI models (LLMs), by contrast, require a separate training mode and inference mode.</p><p>When we chat with a system like ChatGPT, the model is running in inference mode. In this mode, information shared with the model is not written back into its weights. One might argue that ChatGPT has memory and can remember past interactions. This is true, but such memory is implemented through context windows or augmented memory systems. An analogy would be listening to a lecture and, instead of the information being internalized by your brain, you merely write it down in notes. Every time someone asks a question, you refer back to the notes.</p><p>As the title suggests, this topic is about neuroplasticity. The goal is to explore mechanisms in modern artificial intelligence that allow models to learn in the cheapest possible way, without requiring an explicit training mode. I believe general intelligence can only be achieved when a model can learn, update its own weights, and iterate autonomously, without relying on curated training datasets.</p><p>What exactly is neuroplasticity? According to Wikipedia:</p><blockquote><strong>Neuroplasticity</strong>, also known as <strong>neural plasticity</strong> or just <strong>plasticity</strong>, is the medium of neural networks in the brain to change through growth and reorganization. Neuroplasticity refers to the brain’s ability to reorganize and rewire its neural connections, enabling it to adapt and function in ways that differ from its prior state. This process can occur in response to learning new skills, experiencing environmental changes, recovering from injuries, or adapting to sensory or cognitive deficits. Such adaptability highlights the dynamic and ever-evolving nature of the brain, even into adulthood</blockquote><p>From this definition, one might ask: don’t today’s AI models already do this during pre-training and fine-tuning? Yes, but this approach has significant limitations. It requires an explicit training phase involving expensive operations such as backpropagation, carefully formatted datasets, and is vulnerable to catastrophic forgetting (CF).</p><p>If we could achieve at least the following two criteria, my hypothesis is that we could approach general intelligence:</p><ul><li>Efficient weight updates without catastrophic forgetting (plasticity)</li><li>Models that can self-learn from noisy input</li></ul><p>To begin this journey, we will first review existing research from Google:</p><ol><li><a href="https://research.google/blog/titans-miras-helping-ai-have-long-term-memory/">Titans + MIRAS: Helping AI have long-term memory</a></li><li><a href="https://research.google/pubs/learning-without-training-the-implicit-dynamics-of-in-context-learning/">Learning without training: The implicit dynamics of in-context learning</a></li><li><a href="https://research.google/blog/introducing-nested-learning-a-new-ml-paradigm-for-continual-learning/">Introducing Nested Learning: A new ML paradigm for continual learning</a></li></ol><h3>Mathematical Proof</h3><p>In Part 1, we will unpack the second paper: <em>Learning without training</em>.</p><p>The abstract of the research states:</p><blockquote>One of the most striking features of Large Language Models (LLMs) is their ability to learn in-context. Namely at inference time an LLM is able to learn new patterns without any additional weight update when these patterns are presented in the form of examples in the prompt, even if these patterns were not seen during training. The mechanisms through which this can happen are still largely unknown. In this work, we show that the stacking of a self-attention layer with an MLP, allows the transformer block to implicitly modify the weights of the MLP layer according to the context. We argue through theory and experimentation that this simple mechanism may be the reason why LLMs can learn in-context and not only during training. Specifically, we show how a transformer block implicitly transforms a context into a low-rank weight-update of its MLP layer.</blockquote><p>The paper addresses a fundamental mystery in LLMs: how do models “learn” from prompts known as In-Context Learning (ICL) without actually updating their parameters through backpropagation?</p><p>The authors propose that the Transformer architecture enables a form of <strong>“virtual” weight update</strong>. Although the physical weights of the model remain unchanged, the mathematics behaves as if the weights were updated.</p><p>The authors construct a mathematical model to demonstrate the presence of effective weight updates arising from ICL. We will attempt to follow their derivation using more accessible notation, and then use GPT-2 to numerically verify the derived model.</p><p>To follow the mathematics, let’s define the building blocks used in Theorem 2.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMPpgvMpDYX01gXbvQ5pHg.png" /></figure><p>The contextual layer, denoted by <strong>A</strong>, represents the self-attention mechanism. Equation (1) defines the context vector ΔA as the difference between the layer output with context and without context.</p><p>Equation (2) represents the feed-forward (MLP) layer following attention, where <strong>Wz</strong> is the weight and <strong>b</strong> is the bias.</p><p>Equation (3) defines the contextual block, which combines attention and the MLP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmOolPQ7gRX5rZP16lLzGQ.png" /><figcaption>Contextual Block equation</figcaption></figure><p>Equation (4) expands the formula from (2) and (3). This sets up the foundation. The next step is to use a “mathematical trick” to find an equivalent equation in which the context vector is replaced by a weight update.</p><p>Before proceeding, let’s consider a simple algebraic example to build intuition.</p><p>Suppose we have the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8YGdBe0rqeZeSryCzL5Mg.png" /><figcaption>Toy algebra</figcaption></figure><p>In Equation (5.1), we define a function. In Equation (5.2), we add 10 to the result, i.e., f(x) + 10. Instead of representing it as (5.2), we want to express this addition<strong> as a change in the “slope of the line.”</strong> We rewrite the equation as shown in (5.3) and (5.31). In doing so, we need to find a ΔW that satisfies the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNGTrIThott57Ar4WKiW4w.png" /></figure><p>We find that the ΔW in Equation (5.41) satisfies (5.31). We can verify this in (5.42), confirming that (5.31) is equivalent to (5.2).</p><p>This is the same mathematical trick used by the authors. By introducing ΔW into the contextual block expression defined in Equation (4), we can rewrite the expression in a form that resembles a weight update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*if0d-pKZA8W3cSwU0dJagA.png" /></figure><p>Equations (6) through (9) are straightforward algebraic expansions. We substitute Equation (7) into Equation (6) to obtain (8). Equation (7) itself is simply a rearrangement of Equation (1). Equations (10) and (10.1) are the final goal, where we express <strong>W · ΔA</strong> as <strong>ΔW · A(x)</strong> (see the green boxes in Equations (9) and (10)). The final form has the following properties:</p><p>The input to the function is now only <strong>A(x)</strong>, which represents the query without context. The weights are now <strong>W + ΔW</strong>.</p><p>Thus, we arrive at a mathematical proof that the output of the contextual block is equivalent to applying an updated weight matrix to attention without context.</p><p>The next part is the hardest to intuitively grasp: proving that <strong>W · ΔA</strong> can be expressed as <strong>ΔW · A(x)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRazep5ZVMc3dLTu-F56Qg.png" /></figure><p>Starting with Equation (9.2), we use the identity of scalar projection. For any non-zero vector <strong>v</strong>, this expression always evaluates to 1. This can be verified numerically, though it applies to vectors rather than matrices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZT-OcjD4CWtKeggXejcGg.png" /></figure><p>We then construct <strong>A(x)</strong> using this identity. In Equation (9.3), we multiply <strong>W · ΔA</strong> by 1. Since multiplying by 1 does not change the value, the expression remains the same. However, due to the associative property of matrix multiplication, we can rearrange the terms. In Equation (9.4), the expression separates into two components: the left term in brackets and <strong>A(x)</strong> on the right. Referring back to Equation (9.1), the left component can now be denoted as <strong>ΔW</strong>. Thus, we have reconstructed <strong>W · ΔA</strong> as <strong>ΔW · A(x)</strong>.</p><h3>Numerical Verification</h3><p>Now that we have mathematically shown that the model’s weights are virtually updated during in-context learning, we can run a simple experiment to verify this numerically.</p><p>We will use a GPT model for this setup, as it is easier to follow. For a refresher, you may read my previous article <a href="https://medium.com/@mahadir.ahmad/mastering-the-intuition-behind-large-language-model-llm-by-building-gpt-2-from-scratch-6f93bc303cb9"><em>Building Large Language Model (LLM) from Scratch in just 160 Lines of Code</em></a>.</p><p>We place hooks to capture the attention output with context <strong>A(C, x)</strong> and without context <strong>A(x)</strong> from the <strong>LayerNorm 2 output</strong>. We then retrieve the weight and bias from the <strong>feed-forward layer</strong>.</p><blockquote>Actual feed-forward output = weight multiplied by input + bias<br> Derived feed-forward output = Equation (10.1), using ΔW from Equation (9.5)</blockquote><p>If the actual feed-forward output equals the derived feed-forward output, then the formula is numerically verified.</p><p>The following diagram annotates the locations visually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPq0YF6y4VD0_HFklnHGMQ.png" /></figure><p>Concretely, the first hook retrieves <strong>A(x)</strong> and <strong>A(C, x)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCCBr_s0_l6F9QDf3T4hfA.png" /></figure><p>The second hook retrieves the feed-forward parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5isqQsFvFLYCylyHXFoVg.png" /></figure><p>The full code is provided, though for simplicity we use the Hugging Face module with pre-trained weights.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af0b3bd4cbf60c4ea640382515baf33a/href">https://medium.com/media/af0b3bd4cbf60c4ea640382515baf33a/href</a></iframe><p>The output confirms the equivalence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5GdzpZ3c1vlDOnwLWxK8A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e060a4c5e54603ee0b25257d83e54137/href">https://medium.com/media/e060a4c5e54603ee0b25257d83e54137/href</a></iframe><h3>Conclusion</h3><p>In Part 1, we unpack an insight that arguably explains the emerging capabilities of transformer architectures in LLMs specifically, their ability to learn through prompting. The mechanism resembles a form of virtual weight update, analogous to stochastic gradient descent (SGD) during training. In short,<strong> transformers exhibit plasticity during inference</strong>. Unlike traditional training, these virtual weight updates occur at inference time and are significantly more efficient in terms of computation and memory. If we can harness this mechanism, teaching LLMs new knowledge and skills could require far fewer resources.</p><p>I initially planned to include an experiment using LLMs in the 3–10 billion parameter range, combining ICL with LoRA. However, this article has already become too long, so I will cover that in the next part.</p><p>In the next article, we will explore how to harness this insight to unlock continuous learning in LLMs. With this capability of “higher plasticity” we will examine whether such systems can converge toward general intelligence.</p><p>Feel free to give a clap if you find this article useful, and subscribe for notifications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b4a27d05985" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Large Language Model (LLM) from Scratch in just 160 lines of Code]]></title>
            <link>https://medium.com/@mahadir.ahmad/mastering-the-intuition-behind-large-language-model-llm-by-building-gpt-2-from-scratch-6f93bc303cb9?source=rss-f8a461eb6548------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f93bc303cb9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Mahadir Ahmad]]></dc:creator>
            <pubDate>Mon, 12 May 2025 15:45:55 GMT</pubDate>
            <atom:updated>2025-05-16T02:20:06.249Z</atom:updated>
            <content:encoded><![CDATA[<p>My first exposure to the concepts of self-attention and Transformers came a few years ago when I completed the <a href="https://medium.com/r?url=https%3A%2F%2Fwww.coursera.org%2Fspecializations%2Fnatural-language-processing">Natural Language Processing Specialization by DeepLearning.AI</a>. By the end of the course, I was able to follow along and implement encoder-decoder models using example code. However, I found myself lacking a deep, intuitive understanding of the core building blocks particularly the self-attention mechanism.</p><p>It took a significant amount of extra time and effort before these concepts truly clicked. While there are many excellent resources that explain self-attention, this article is my personal attempt to share the intuition I’ve built — through visuals and hands-on code examples. My hope is that you’ll walk away with the same clarity I eventually gained.</p><p>To ground our understanding, we’ll rebuild GPT-2 from the ground up. GPT-2 is a <strong>decoder-only Transformer</strong>, unlike the original Transformer architecture introduced in the <a href="https://arxiv.org/abs/1706.03762">seminal 2017 paper</a>, which featured both encoder and decoder components and was primarily used for machine translation. Decoder-only models like GPT-2, however, demonstrate the powerful emergent ability to perform a variety of tasks including translation and question-answering without needing an encoder.</p><p>By understanding the core mechanics of GPT-2, you’ll unlock insight into nearly every modern state-of-the-art language model. These models differ mainly in optimization techniques, such as improved positional encodings or better attention mechanisms.</p><blockquote><strong>Note</strong>: This article assumes a working knowledge of machine learning, linear algebra, and Python (PyTorch).</blockquote><h3>Architecture Overview</h3><p>Here’s a high-level architectural diagram of GPT-2 to orient our journey:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*wiApQEdLRaR5BNAU85LauA.png" /></figure><p>The model flows <strong>bottom-up</strong>: beginning with text tokenization, moving through embeddings and attention blocks, and finally producing a probability distribution for the next token. Let’s begin with tokenization.</p><h3>Tokenization</h3><p>Since LLMs operate on numerical input, the first step is converting text into numbers. This involves mapping each word or subword in the corpus to a unique ID — a process that requires a vocabulary lookup.</p><p>For English, this can mean up to a million unique entries, which is computationally expensive. GPT-2 uses <strong>Byte Pair Encoding (BPE)</strong>, which provides a compact vocabulary of 50,257 tokens.</p><p>Let’s try tokenizing the sentence:</p><blockquote>“Hi, do you like Nasi Lemak?”</blockquote><pre>pip install tiktoken</pre><pre>import tiktoken<br><br>print(tokenizer.n_vocab)<br># 50257<br><br>text = (<br>&quot;Hi, do you like Nasi Lemak?&lt;|endoftext|&gt;&quot;<br>)<br>integers = tokenizer.encode(text, allowed_special={&quot;&lt;|endoftext|&gt;&quot;})<br>print(integers)<br><br># [17250, 11, 466, 345, 588, 399, 17053, 20607, 461, 30, 220, 50256]</pre><p>The tokenizer will return a list of integers corresponding to the subword tokens.</p><h3>Embeddings</h3><p>Token IDs are just integers with no semantic meaning. For example, 17250 (Hi) being greater than 345 (you) has no contextual significance.</p><p><strong>Embeddings</strong> solve this by mapping tokens to high-dimensional vectors that encode semantic information. For GPT-2, the embedding size is 768, so we create an embedding matrix of size 50257 x 768 (vocabulary size × embedding dimension).</p><p>In PyTorch, implementing embeddings is straightforward:</p><pre><br>vocab_size = 50257<br>embedding_dim = 768<br>embedding_layer = torch.nn.Embedding(vocab_size, embedding_dim)<br>print(embedding_layer.weight)</pre><h3>Positional Encoding</h3><p>While embeddings capture <strong>what</strong> the words mean, they don’t capture <strong>where</strong> they appear. For example, the sentences:</p><p>“Malaysian eats Nasi Lemak”</p><p>“Nasi Lemak eats Malaysian”</p><p>have drastically different meanings but the same tokens.</p><p>To add positional awareness, we use <strong>positional encodings</strong>. There are two main types:</p><p><strong>Absolute</strong> (based on sequence position)</p><p><strong>Relative</strong> (based on distance between tokens)</p><p>Recent models like LLaMA use <strong>Rotary Positional Embeddings (RoPE)</strong>. But for simplicity, we’ll use absolute positional encoding here.</p><p>We can now package tokenization, embedding, and positional encoding into a clean PyTorch class:</p><pre>import torch.nn.functional as F<br>import torch<br>import torch.nn as nn<br><br>class Config:<br>    def __init__(self):<br>      self.vocab_size =  50257<br>      self.embedding_dim = 768<br>      self.drop_rate = 0.1<br>      self.transformer_layer = 12<br>      self.attention_head = 12<br>      self.context_length = 1024<br><br>class GPTModel(nn.Module):<br><br>    def __init__(self, cfg):<br>        super().__init__()<br>        self.token_embedding = nn.Embedding(cfg.vocab_size, cfg.embedding_dim)<br>        self.positional_embedding = nn.Embedding(cfg.vocab_size, cfg.embedding_dim)<br>        self.dropout = nn.Dropout(cfg.drop_rate)<br><br>        # TODO transformer layer<br><br>    def forward(self, in_idx):<br><br>        batch_size, seq_len = in_idx.shape<br>        token_embedding = self.token_embedding(in_idx)<br>        positional_embedding = self.positional_embedding(torch.arange(seq_len, device=in_idx.device))<br>        x = token_embedding + positional_embedding<br>        x = self.dropout(x)<br><br>        # TODO transformer<br>        return x</pre><h3>Transformer Block</h3><p>The transformer block is the heart of the model, housing the critical <strong>Multi-Head Attention (MHA)</strong> mechanism. GPT-2 has 12 such blocks, each with 12 attention heads.</p><p>Here’s what it looks like visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*CrPXB5oPHdk6bs5stNpcUw.png" /></figure><h3>Multi Head Attention</h3><p>Let’s dive into <strong>self-attention</strong>, which is powered by three components: <strong>Queries (Q)</strong>, <strong>Keys (K)</strong>, and <strong>Values (V)</strong>. These are learned projections that allow the model to dynamically “attend” to different parts of the input.</p><p>Imagine the sentence:</p><blockquote><em>“I ate nasi lemak with spicy sambal and crunchy anchovies.”</em></blockquote><p>The word “sambal” should relate strongly to “spicy” and “nasi lemak.” Self-attention helps establish these relationships.</p><p>We compute attention weights using <strong>dot products</strong> between the Q and K vectors for each token, which are then used to weigh the V vectors. Here’s a heatmap visualization of the attention weights may look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eegFHk_QaCSplY0sA0f-GA.png" /></figure><p>How this relate to QKV then? Let’s say for the above sentence</p><pre>inx = tokenizer.encode(&quot;I ate nasi lemak with spicy sambal and crunchy anchovies&quot;)<br>config = Config()<br>model = GPTModel(config)<br>out = model(torch.tensor(inx).unsqueeze(0))<br>print(out.shape)<br># torch.Size([1, 17, 768])</pre><p>Converting into token embeding will produced the size of 17 x 768. 17 is the size of token ID and 768 is the embedding size for every token ID. How do you then calculate the similarity? Using vector computation we can use cosine similarity approach for calculating the distance similarity between the words. This can be easily done using the dot product with itself.</p><pre># clone out into Q<br>Q = out<br># clone out into K<br>K = out<br># apply dot product, 1x17x768 @ 1x768x17<br>attention_score = Q @ K.transpose(-2,-1)<br>print(attention_score.shape)<br># torch.Size([1, 17, 17])</pre><p>This QKV itself are weights that will be learned during the training, so what we need to do is create a linear vector using pyTorch</p><pre>W_Q = nn.Linear(config.embedding_dim, config.embedding_dim)<br>W_K = nn.Linear(config.embedding_dim, config.embedding_dim)<br>W_V = nn.Linear(config.embedding_dim, config.embedding_dim)<br><br>Q = W_Q(out)<br>K = W_K(out)<br>V = W_K(out)<br><br>attention_score = Q @ K.transpose(-2,-1)<br><br># apply softmax<br>attn_weights = F.softmax(attention_score, dim=-1)<br><br># apply matrix multiplication, <br># each row of the att w is dotted product with column in V<br># 1x17x17 @ 1x17x768 -&gt; 1x17x768<br>context = attn_weights @ V</pre><h4>Causal Mask</h4><p>Because GPT-2 is used for <strong>next-token prediction</strong>, it must not “see” future tokens during training. To prevent this, we apply a <strong>causal mask</strong> that sets the upper triangle of the attention matrix to -∞, which forces the model to attend only to past tokens. Following is a toy example of applying the mask on input of 5x5</p><pre>mask = torch.triu(torch.ones(5, 5), diagonal=1)<br>mask = mask[:5, :5] == 1<br>x = torch.randn(5,5)<br>x = x.masked_fill(mask, float(&#39;-inf&#39;))<br>print(mask)<br>print(&quot;\n\n&quot;)<br>print(x)<br><br>#tensor([[False,  True,  True,  True,  True],<br>#        [False, False,  True,  True,  True],<br>#        [False, False, False,  True,  True],<br>#        [False, False, False, False,  True],<br>#        [False, False, False, False, False]])<br><br><br><br>#tensor([[-0.6267,    -inf,    -inf,    -inf,    -inf],<br>#        [-0.3315,  0.3031,    -inf,    -inf,    -inf],<br>#        [ 0.4817,  1.0656, -0.5865,    -inf,    -inf],<br>#        [-0.9612, -1.4964,  0.0038,  1.6447,    -inf],<br>#        [ 0.8002, -1.1182,  0.7470,  0.6025,  0.0161]])</pre><p>This masked attention is passed through softmax to convert scores into a probability distribution. When negative infinity values (-∞) are present in a row, the softmax function treats them as zero probability. (Mathematically, this is because e–∞ approaches 0.). Now we can update our code above with the masked attention.</p><pre>mask = torch.triu(torch.ones(config.embedding_dim, config.embedding_dim), diagonal=1)<br>mask = mask[:config.embedding_dim, :config.embedding_dim] == 1<br>attention_score = attention_score.masked_fill(mask, float(&#39;-inf&#39;))<br><br># apply softmax<br>attn_weights = F.softmax(attention_score, dim=-1)<br><br># apply matrix multiplication, <br># each row of the att w is dotted product with column in V<br># 1x17x17 @ 1x17x768 -&gt; 1x17x768<br>context = attn_weights @ V</pre><p>In the final cleaned codes, we will add few extra processing such as scaling the attention score to make it more stable, dropout and linear projection as the objective of each heads is to focus on certain aspect of the sentence. Overall the visual flow of the attention head like depicted in the following image. Note that the input size is displayed as 10 instead of 17 for illustration purpose because we did not convert the sentence into token ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zg8YO5t80b41FaHT82_yCw.png" /></figure><p>Let’s code the transformer block and the attention head into MultiHeadAttention and TransformerLayer class accordingly. One important part that you will need to take note is the Attention Head inside each of the layer is executed in parallel through a vectorized operation.</p><p>Consider a toy example below to understand the idea behind the vectorized approach of the MHA.</p><pre># Consider the head is 2<br>x = torch.tensor([[<br>  [1.0, 2.0, 3.0, 4.0],   # token 1<br>  [5.0, 6.0, 7.0, 8.0]    # token 2<br>]])<br>print(&quot;original shape&quot;, x.shape)<br><br># Linear projection<br>W_q = torch.tensor([<br>  [1.0, 0.0, 0.0, 0.0],<br>  [0.0, 1.0, 0.0, 0.0],<br>  [0.0, 0.0, 1.0, 0.0],<br>  [0.0, 0.0, 0.0, 1.0]<br>])<br><br>Q = x @ W_q <br>#tensor([[1., 2., 3., 4.],<br>#        [5., 6., 7., 8.]])<br><br># reshape the vector from [2, 4] → [2, 2, 2] → 2 tokens, 2 heads, 2 dims per head:<br>Q = Q.view(1,2, 2, 2)<br>print(&quot;The tokens are splitted equally into heads&quot;,Q.shape)<br>#[<br>#  [[1.0, 2.0], [3.0, 4.0]],   # token 1 → head 0 and head 1<br>#  [[5.0, 6.0], [7.0, 8.0]]    # token 2 → head 0 and head 1<br>#]<br><br># for demo purpose we simply clone the Q<br>K = Q<br>V = Q<br><br># Compute the score inside every heads in parallel<br>score = Q @ K.transpose(1,2)<br>context = score @ V<br><br># combine the scores<br>context = context.transpose(1, 2).contiguous().view(1, 2, -1)<br>print(&quot;the shape of the final score&quot;, context.shape)</pre><p>The full code of the MHA</p><pre>class MultiHeadAttention(nn.Module):<br>    def __init__(self, dim_in, dim_out, context_length, dropout, num_heads):<br>        super().__init__()<br>        assert dim_out % num_heads == 0, &quot;dim_out must be divisible by num_heads&quot;<br><br>        self.num_heads = num_heads<br>        self.head_dim = dim_out // num_heads<br>        self.scale = self.head_dim ** -0.5  # For scaling dot product<br><br>        # Q, K, V projections<br>        self.W_q = nn.Linear(dim_in, dim_out)<br>        self.W_k = nn.Linear(dim_in, dim_out)<br>        self.W_v = nn.Linear(dim_in, dim_out)<br><br>        # Final output projection<br>        self.out_proj = nn.Linear(dim_out, dim_out)<br><br>        # Dropout<br>        self.dropout = nn.Dropout(dropout)<br><br>        # Causal mask (upper triangular matrix)<br>        mask = torch.triu(torch.ones(context_length, context_length), diagonal=1)<br>        # exclude this mask from being updated during backward<br>        self.register_buffer(&quot;mask&quot;, mask)<br><br>    def forward(self, x):<br>        batch_size, embed_size, _ = x.size()  # Batch, embed_size, Features<br><br>        # Linear projections<br>        Q = self.W_q(x)  # (batch_size, embed_size, dim_out)<br>        K = self.W_k(x)<br>        V = self.W_v(x)<br><br>        # Split the features equally into every heads<br>        Q = Q.view(batch_size, embed_size, self.num_heads, self.head_dim).transpose(1, 2)  # (batch_size, num_heads, embed_size, head_dim)<br>        K = K.view(batch_size, embed_size, self.num_heads, self.head_dim).transpose(1, 2)<br>        V = V.view(batch_size, embed_size, self.num_heads, self.head_dim).transpose(1, 2)<br><br>        # Attention scores<br>        attention_scores = (Q @ K.transpose(-2, -1)) * self.scale  # (batch_size, num_heads, embed_size, embed_size)<br><br>        # Apply causal mask<br>        mask = self.mask[:embed_size, :embed_size] == 1<br>        attention_scores = attn_scores.masked_fill(mask, float(&#39;-inf&#39;))<br><br>        # Softmax and dropout<br>        attention_weights = F.softmax(attention_scores, dim=-1)<br>        attention_weights = self.dropout(attention_weights)<br><br>        # Weighted sum of values<br>        context = attention_weights @ V  # (B, num_heads, embed_size, head_dim)<br>        context = context.transpose(1, 2).contiguous().view(batch_size, embed_size, -1)  # (batch_size, embed_size, dim_out)<br><br>        return self.out_proj(context)</pre><h3>Transformer</h3><p>With attention and transformer blocks ready, we can now construct the full GPT-2 model by stacking 12 layers, adding layer normalization, GELU activations, and feedforward networks.</p><pre>class LayerNorm(nn.Module):<br><br>    def __init__(self, embed_dim):<br>        super().__init__()<br>        self.eps = 1e-5 # epsilon, small num to prevent dividing 0<br>        self.scale = nn.Parameter(torch.ones(embed_dim))<br>        self.shift = nn.Parameter(torch.zeros(embed_dim))<br><br>    def forward(self, x):<br>        mean = x.mean(dim=-1, keepdim=True)<br>        var = x.var(dim=-1, keepdim=True, unbiased=False)<br>        norm_x = (x-mean) / torch.sqrt(var+self.eps)<br>        return self.scale * norm_x + self.shift<br><br><br>class GELU(nn.Module):<br><br>    def __init__(self):<br>        super().__init__()<br><br>    def forward(self, x):<br>        return 0.5 * x * (1 + torch.tanh(torch.sqrt(torch.tensor(2.0 / torch.pi)) * (x + 0.044715 * torch.pow(x,3)) ))<br><br><br>class FeedForward(nn.Module):<br><br>    def __init__(self, dim):<br>        super().__init__()<br>        self.layers = nn.Sequential(<br>            nn.Linear(dim, 4 * dim),<br>            GELU(),<br>            nn.Linear(4 * dim, dim),<br>        )<br><br>    def forward(self, x):<br>        return self.layers(x)<br><br><br>class TransformerLayer(nn.Module):<br><br>    def __init__(self, config):<br>        super().__init__()<br>        self.att = MultiHeadAttention(<br>            dim_in = config.embedding_dim,<br>            dim_out = config.embedding_dim,<br>            context_length = config.context_length,<br>            num_heads=config.attention_head,<br>            dropout=config.drop_rate<br>        )<br>        self.ff = FeedForward(config.embedding_dim)<br>        self.norm1 = LayerNorm(config.embedding_dim)<br>        self.norm2 = LayerNorm(config.embedding_dim)<br>        self.drop_shortcut = nn.Dropout(config.drop_rate)<br><br>    def forward(self, x):<br>        residual1 = x<br>        x = self.norm1(x)<br>        x = self.att(x)<br>        x = self.drop_shortcut(x)<br>        x = x + residual1<br>        residual2 = x<br>        x = self.norm2(x)<br>        x = self.ff(x)<br>        x = self.drop_shortcut(x)<br>        x = x + residual2<br>        return x</pre><p>And finally we can update the GPTModel we created earlier to include the transformer layers. The full codes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd1be604bef7a3674d4909f58f78859a/href">https://medium.com/media/dd1be604bef7a3674d4909f58f78859a/href</a></iframe><p>Let’s run the model.</p><pre>def generate_text_simple(model, idx, max_new_tokens, context_size):<br>    # idx is (B, T) array of indices in the current context<br>    for _ in range(max_new_tokens):<br><br>        # Crop current context if it exceeds the supported context size<br>        # E.g., if LLM supports only 5 tokens, and the context size is 10<br>        # then only the last 5 tokens are used as context<br>        idx_cond = idx[:, -context_size:]<br><br>        # Get the predictions<br>        with torch.no_grad():<br>            logits = model(idx_cond)<br><br>        # Focus only on the last time step<br>        # (batch, n_token, vocab_size) becomes (batch, vocab_size)<br>        logits = logits[:, -1, :]<br><br>        # Get the idx of the vocab entry with the highest logits value<br>        idx_next = torch.argmax(logits, dim=-1, keepdim=True)  # (batch, 1)<br><br>        # Append sampled index to the running sequence<br>        idx = torch.cat((idx, idx_next), dim=1)  # (batch, n_tokens+1)<br><br>    return idx<br><br>config = Config()<br>model = GPTModel(config)<br>model.eval() <br><br>start_context = &quot;I ate nasi lemak with spicy sambal and crunchy&quot;<br><br>tokenizer = tiktoken.get_encoding(&quot;gpt2&quot;)<br>encoded = tokenizer.encode(start_context)<br>encoded_tensor = torch.tensor(encoded).unsqueeze(0)<br><br>print(f&quot;\n{50*&#39;=&#39;}\n{22*&#39; &#39;}IN\n{50*&#39;=&#39;}&quot;)<br>print(&quot;\nInput text:&quot;, start_context)<br>print(&quot;Encoded input text:&quot;, encoded)<br>print(&quot;encoded_tensor.shape:&quot;, encoded_tensor.shape)<br><br>out = generate_text_simple(<br>        model=model,<br>        idx=encoded_tensor,<br>        max_new_tokens=10,<br>        context_size=config.context_length<br>    )<br>decoded_text = tokenizer.decode(out.squeeze(0).tolist())<br><br>print(f&quot;\n\n{50*&#39;=&#39;}\n{22*&#39; &#39;}OUT\n{50*&#39;=&#39;}&quot;)<br>print(&quot;\nOutput:&quot;, out)<br>print(&quot;Output length:&quot;, len(out[0]))<br>print(&quot;Output text:&quot;, decoded_text)</pre><p>At this point, the output will be gibberish because the weights are not yet trained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJvmti6n90d9LTZnATaa1A.png" /></figure><h4>Training the model</h4><p>For the sake of completeness, let’s train it with a simple toy dataset. For example, you might train it on sentences about food.</p><pre># sample_cuisine.txt<br>cuisine_data = [<br>    &quot;I ate nasi lemak with spicy sambal and crunchy anchovies&quot;,<br>    &quot;Roti canai is best with dhal curry&quot;,<br>    &quot;Chicken biryani with raita is delicious&quot;,<br>    &quot;Beef rendang is spicy and tender&quot;,<br>    &quot;Laksa with boiled egg and tofu is amazing&quot;,<br>    &quot;Satay with peanut sauce is sweet and savory&quot;<br>]<br><br>with open(&quot;cuisine.txt&quot;, &quot;w&quot;) as f:<br>    for line in cuisine_data:<br>        f.write(line + &quot;\n&quot;)</pre><p>And the training loop:</p><pre>from torch.utils.data import Dataset, DataLoader<br><br>class CuisineDataset(Dataset):<br>    def __init__(self, data, tokenizer, block_size=32):<br>        self.tokenizer = tokenizer<br>        self.data = tokenizer.encode(data)<br>        self.block_size = block_size<br><br>    def __len__(self):<br>        return len(self.data) - self.block_size<br><br>    def __getitem__(self, idx):<br>        chunk = self.data[idx:idx + self.block_size + 1]<br>        x = torch.tensor(chunk[:-1], dtype=torch.long)<br>        y = torch.tensor(chunk[1:], dtype=torch.long)<br>        return x, y<br><br><br>def train(model, dataloader, optimizer, epochs=10):<br>    model.train()<br>    for epoch in range(epochs):<br>        total_loss = 0<br>        for xb, yb in dataloader:<br>            optimizer.zero_grad()<br>            logits = model(xb)<br>            loss = F.cross_entropy(logits.view(-1, logits.size(-1)), yb.view(-1))<br>            loss.backward()<br>            optimizer.step()<br>            total_loss += loss.item()<br>        print(f&quot;Epoch {epoch+1} Loss: {total_loss:.4f}&quot;)<br><br>with open(&quot;cuisine.txt&quot;, &quot;r&quot;) as f:<br>    raw_text = f.read()<br><br># Prepare dataset<br>dataset = CuisineDataset(raw_text, tokenizer)<br>dataloader = DataLoader(dataset, batch_size=2)<br><br># Train<br>optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)<br>train(model, dataloader, optimizer, epochs=10)<br><br># Save model<br>torch.save(model.state_dict(), &quot;gpt_cuisine.pt&quot;)<br><br># to load again<br># model.load_state_dict(torch.load(&quot;gpt_cuisine.pt&quot;))</pre><p>Once training finishes, the weights will be saved in a file (e.g., gpt_cuisine.pt) which can be loaded or shared.</p><p>This toy model is a tiny example of what’s referred to as a <strong>foundation model</strong> a large model trained on massive text corpora, which can later be fine-tuned for specific tasks like classification, summarization, or question-answering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f93bc303cb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finetune Qwen-2.5 AI Model for Chain-of-Thought (CoT)]]></title>
            <link>https://medium.com/@mahadir.ahmad/finetune-qwen-2-5-ai-model-for-chain-of-thought-cot-4d1eae3a3aa9?source=rss-f8a461eb6548------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d1eae3a3aa9</guid>
            <category><![CDATA[nvidia-h100]]></category>
            <category><![CDATA[qwen]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chain-of-thought]]></category>
            <dc:creator><![CDATA[Mahadir Ahmad]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 20:16:44 GMT</pubDate>
            <atom:updated>2025-02-07T16:30:45.301Z</atom:updated>
            <content:encoded><![CDATA[<p>Few years back I published an article about getting started with <a href="https://medium.com/@mahadir.ahmad/how-to-parse-billion-of-user-agents-using-pyspark-f57e680727e7">Big Data</a> and demystifying its cost. Unlike data processing, which is mostly deterministic, training neural networks especially large ones is not only expensive but requires patience and creativity. I believe that once we understand the core concepts, successful model training becomes more art than science.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rs7rL3tAZ9rDyUIU" /></figure><p>Recently, the release of DeepSeek R1, which performs reasoning on par with OpenAI’s O1 but reportedly costs only 1/1000 of what Western AI laboratories spend on LLM training, has sparked widespread interest, including my own. In search of a better understanding, I investigated some “proof of concept” examples that helped me experience “aha moments” with the model.</p><p>There are several approaches to fine-tuning language models using Reinforcement Learning from Human Feedback (RLHF). The commonly used method is <a href="https://huggingface.co/docs/trl/main/en/ppo_trainer">PPO</a> (Proximal Policy Optimization), while a recent research paper from DeepSeek introduced <a href="https://huggingface.co/docs/trl/main/en/grpo_trainer">GRPO</a> (Group Relative Policy Optimization).</p><p>I found two helpful resources that helped me get started:</p><ol><li>GRPO — <a href="https://gist.github.com/willccbb/4676755236bb08cab5f4e54a0475d6fb">Gist</a></li><li>Proximal Policy Optimization — <a href="https://github.com/Jiayi-Pan/TinyZero/tree/main">TinyZero</a></li></ol><p>I’ve allocated $30 for experimenting these 2 models, and I’ve used <a href="https://runpod.io/?ref=grcc6zsa">RunPod</a> ( the link is an affiliate link, feel free to click and register through it if you find this article helpful :).</p><p>Despite using H100 GPUs, I encountered persistent out-of-memory issues for the PPO training and spent 2–3 hours with dual H100s just for troubleshooting, consuming half of my allocated budget. If you’ve successfully trained models under similar configurations, please share your experience in the comments.</p><p>Followings are my setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4ebeXoQGL0cpcDKM6szow.png" /><figcaption>The Pod — 64 vCPU, 500 GB RAM and 2 x H100 PCIe</figcaption></figure><p>and the specific commands used to start the trainer:</p><pre>wandb login<br>mkdir dataset<br>mkdir model<br><br>export N_GPUS=2<br>export BASE_MODEL=Qwen/Qwen2.5-3B-Instruct<br>export DATA_DIR=dataset<br>export ROLLOUT_TP_SIZE=2<br>export EXPERIMENT_NAME=countdown-qwen2.5-3b<br>export VLLM_ATTENTION_BACKEND=XFORMERS<br><br>python3 -m verl.trainer.main_ppo \<br>data.train_files=$DATA_DIR/train.parquet \<br>data.val_files=$DATA_DIR/test.parquet \<br>data.train_batch_size=256 \<br>data.val_batch_size=1312 \<br>data.max_prompt_length=256 \<br>data.max_response_length=1024 \<br>actor_rollout_ref.model.path=$BASE_MODEL \<br>actor_rollout_ref.actor.optim.lr=1e-6 \<br>actor_rollout_ref.actor.ppo_mini_batch_size=64 \<br>actor_rollout_ref.actor.ppo_micro_batch_size=1 \<br>actor_rollout_ref.rollout.log_prob_micro_batch_size=8 \<br>actor_rollout_ref.rollout.tensor_model_parallel_size=$ROLLOUT_TP_SIZE \<br>actor_rollout_ref.rollout.gpu_memory_utilization=0.4 \<br>critic.optim.lr=1e-5 \<br>critic.model.path=$BASE_MODEL \<br>critic.ppo_micro_batch_size=1 \<br>algorithm.kl_ctrl.kl_coef=0.001 \<br>trainer.logger=[&#39;wandb&#39;] \<br>+trainer.val_before_train=False \<br>trainer.default_hdfs_dir=null \<br>trainer.n_gpus_per_node=$N_GPUS \<br>trainer.nnodes=1 \<br>trainer.save_freq=10 \<br>trainer.test_freq=10 \<br>trainer.default_hdfs_dir=model \<br>trainer.project_name=TinyZero \<br>trainer.experiment_name=$EXPERIMENT_NAME \<br>trainer.total_epochs=15 2&gt;&amp;1 | tee verl_demo.log</pre><p>I decided to move on to the GRPO approach so let’s examine the GRPO approach step by step, which hopefully can provide valuable insights for future reference.</p><h4>Step by Step for Getting the machine up and running</h4><ol><li>Register for a <a href="https://runpod.io/?ref=grcc6zsa">RunPod</a> account if you don’t one yet ( again the link is an affiliate, feel free to click and register through it if you find this article helpful :).</li></ol><p>2. Navigate to Pods in the menu and click Deploy</p><p>3. Select H100 PCIe and choose RunPod Pytorch 2.1 as the template. The on-demand option costs $2.39/hour, so it’s our best interest to get the trainer up and running as soon as possible. In the future, I’ll consider exploring the Spot optio, as it costs half the price since it’s possible to tolerate interruptions with aggressive checkpointing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1VqQHblaH6LiS8ntNvcLmQ.png" /></figure><p>4. Once the Pod is ready, click the Burger Icon -&gt; Edit Pod and adjust the Volume disk to at least 100GB. Save the changes, this will restart the pod. it’s better do complete this step in the beginning rather than have to do this halfway while the trainer is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eG5wmV60ml7Qe2KyIjlGqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pXFT9N2DygoB5ebhJEn0w.png" /><figcaption>Adjust the volume disk</figcaption></figure><p>5. Once the Pod is ready, click connect and choose Jupyter Lab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gPhCRH7mqLTuKEd5h55gw.png" /></figure><p>6. Open File -&gt; New -&gt; Terminal to install required packages (5–10 minutes). Alternatively, we can also build a docker image with pre-installed packages to save time. I’ve included the package versions as well to in case needed for troubleshooting.</p><pre>pip3 install torch==2.4.0 <br>pip3 install flash_attn==2.7.4.post1 --no-build-isolation<br>pip install trl==0.14.0 datasets==3.2.0 transformers==4.48.2 peft==0.14.0 wandb==0.19.5<br>pip install bitsandbytes==0.45.1<br><br>export HF_HOME=&quot;/workspace/huggingface&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*ZYoHxw6QKwco_5UYQGZOMQ.png" /><figcaption>Type the commands above into the terminal</figcaption></figure><p>7. Create a python file. File -&gt; New -&gt; Python File and paste the following codes. Let’s give it a name <strong>trainer.py</strong></p><pre># train_grpo.py<br>import re<br>import torch<br>from datasets import load_dataset, Dataset<br>from transformers import AutoTokenizer, AutoModelForCausalLM<br>from peft import LoraConfig<br>from trl import GRPOConfig, GRPOTrainer<br><br># Load and prep dataset<br><br>SYSTEM_PROMPT = &quot;&quot;&quot;<br>Respond in the following format:<br>&lt;reasoning&gt;<br>...<br>&lt;/reasoning&gt;<br>&lt;answer&gt;<br>...<br>&lt;/answer&gt;<br>&quot;&quot;&quot;<br><br>XML_COT_FORMAT = &quot;&quot;&quot;\<br>&lt;reasoning&gt;<br>{reasoning}<br>&lt;/reasoning&gt;<br>&lt;answer&gt;<br>{answer}<br>&lt;/answer&gt;<br>&quot;&quot;&quot;<br><br>def extract_xml_answer(text: str) -&gt; str:<br>    answer = text.split(&quot;&lt;answer&gt;&quot;)[-1]<br>    answer = answer.split(&quot;&lt;/answer&gt;&quot;)[0]<br>    return answer.strip()<br><br>def extract_hash_answer(text: str) -&gt; str | None:<br>    if &quot;####&quot; not in text:<br>        return None<br>    return text.split(&quot;####&quot;)[1].strip()<br><br># uncomment middle messages for 1-shot prompting<br>def get_gsm8k_questions(split = &quot;train&quot;) -&gt; Dataset:<br>    data = load_dataset(&#39;openai/gsm8k&#39;, &#39;main&#39;)[split] # type: ignore<br>    data = data.map(lambda x: { # type: ignore<br>        &#39;prompt&#39;: [<br>            {&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: SYSTEM_PROMPT},<br>            #{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: &#39;What is the largest single-digit prime number?&#39;},<br>            #{&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: XML_COT_FORMAT.format(<br>            #    reasoning=&quot;9 is divisble by 3 and 8 is divisible by 2, but 7 is prime.&quot;,<br>            #    answer=&quot;7&quot;<br>            #)},<br>            {&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: x[&#39;question&#39;]}<br>        ],<br>        &#39;answer&#39;: extract_hash_answer(x[&#39;answer&#39;])<br>    }) # type: ignore<br>    return data # type: ignore<br><br>dataset = get_gsm8k_questions()<br><br># Reward functions<br>def correctness_reward_func(prompts, completions, answer, **kwargs) -&gt; list[float]:<br>    responses = [completion[0][&#39;content&#39;] for completion in completions]<br>    q = prompts[0][-1][&#39;content&#39;]<br>    extracted_responses = [extract_xml_answer(r) for r in responses]<br>    print(&#39;-&#39;*20, f&quot;Question:\n{q}&quot;, f&quot;\nAnswer:\n{answer[0]}&quot;, f&quot;\nResponse:\n{responses[0]}&quot;, f&quot;\nExtracted:\n{extracted_responses[0]}&quot;)<br>    return [2.0 if r == a else 0.0 for r, a in zip(extracted_responses, answer)]<br><br>def int_reward_func(completions, **kwargs) -&gt; list[float]:<br>    responses = [completion[0][&#39;content&#39;] for completion in completions]<br>    extracted_responses = [extract_xml_answer(r) for r in responses]<br>    return [0.5 if r.isdigit() else 0.0 for r in extracted_responses]<br><br>def strict_format_reward_func(completions, **kwargs) -&gt; list[float]:<br>    &quot;&quot;&quot;Reward function that checks if the completion has a specific format.&quot;&quot;&quot;<br>    pattern = r&quot;^&lt;reasoning&gt;\n.*?\n&lt;/reasoning&gt;\n&lt;answer&gt;\n.*?\n&lt;/answer&gt;\n$&quot;<br>    responses = [completion[0][&quot;content&quot;] for completion in completions]<br>    matches = [re.match(pattern, r) for r in responses] <br>    return [0.5 if match else 0.0 for match in matches]<br><br>def soft_format_reward_func(completions, **kwargs) -&gt; list[float]:<br>    &quot;&quot;&quot;Reward function that checks if the completion has a specific format.&quot;&quot;&quot;<br>    pattern = r&quot;&lt;reasoning&gt;.*?&lt;/reasoning&gt;\s*&lt;answer&gt;.*?&lt;/answer&gt;&quot;<br>    responses = [completion[0][&quot;content&quot;] for completion in completions]<br>    matches = [re.match(pattern, r) for r in responses] <br>    return [0.5 if match else 0.0 for match in matches]<br><br>def count_xml(text) -&gt; float:<br>    count = 0.0<br>    if text.count(&quot;&lt;reasoning&gt;\n&quot;) == 1:<br>        count += 0.125<br>    if text.count(&quot;\n&lt;/reasoning&gt;\n&quot;) == 1:<br>        count += 0.125<br>    if text.count(&quot;\n&lt;answer&gt;\n&quot;) == 1:<br>        count += 0.125<br>        count -= len(text.split(&quot;\n&lt;/answer&gt;\n&quot;)[-1])*0.001<br>    if text.count(&quot;\n&lt;/answer&gt;&quot;) == 1:<br>        count += 0.125<br>        count -= (len(text.split(&quot;\n&lt;/answer&gt;&quot;)[-1]) - 1)*0.001<br>    return count<br><br>def xmlcount_reward_func(completions, **kwargs) -&gt; list[float]:<br>    contents = [completion[0][&quot;content&quot;] for completion in completions]<br>    return [count_xml(c) for c in contents]<br><br>#model_name = &quot;meta-llama/Llama-3.2-1B-Instruct&quot;<br>model_name = &quot;Qwen/Qwen2.5-1.5B-Instruct&quot;<br><br>if &quot;Llama&quot; in model_name:<br>    output_dir = &quot;outputs/Llama-1B-GRPO&quot;<br>    run_name = &quot;Llama-1B-GRPO-gsm8k&quot;<br>else:<br>    output_dir=&quot;outputs/Qwen-1.5B-GRPO&quot;<br>    run_name=&quot;Qwen-1.5B-GRPO-gsm8k&quot;<br>    <br>training_args = GRPOConfig(<br>    output_dir=output_dir,<br>    run_name=run_name,<br>    learning_rate=5e-6,<br>    adam_beta1 = 0.9,<br>    adam_beta2 = 0.99,<br>    weight_decay = 0.05,<br>    bf16=True,<br>    warmup_ratio = 0.1,<br>    lr_scheduler_type=&#39;cosine&#39;,<br>    logging_steps=1,<br>    per_device_train_batch_size=1,<br>    gradient_accumulation_steps=2,<br>    num_generations=8,<br>    max_prompt_length=256,<br>    max_completion_length=786,<br>    num_train_epochs=1,<br>    save_steps=10,<br>    max_grad_norm=0.1,<br>    report_to=&quot;wandb&quot;,<br>    log_on_each_node=False,<br>    save_total_limit=5<br>)<br>peft_config = LoraConfig(<br>    r=16,<br>    lora_alpha=64,<br>    target_modules=[&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;, &quot;gate_proj&quot;],<br>    task_type=&quot;CAUSAL_LM&quot;,<br>    lora_dropout=0.05,<br>)<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_name,<br>    attn_implementation=&quot;flash_attention_2&quot;,<br>    torch_dtype=torch.bfloat16,<br>    device_map=&quot;auto&quot;<br>).to(&quot;cuda&quot;)<br>        <br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>tokenizer.pad_token = tokenizer.eos_token<br><br># use peft at your own risk; not working for me with multi-GPU training<br>trainer = GRPOTrainer(<br>    model=model,<br>    processing_class=tokenizer,<br>    reward_funcs=[<br>        xmlcount_reward_func,<br>        soft_format_reward_func,<br>        strict_format_reward_func,<br>        int_reward_func,<br>        correctness_reward_func],<br>    args=training_args,<br>    train_dataset=dataset,<br>    #peft_config=peft_config<br>)<br>trainer.train(resume_from_checkpoint=True)</pre><p>Notable Changes to the Original Trainer Code, to address the out-of-memory issues:</p><ul><li>Initially after the first encounter OOM I’ve enabled <strong>gradient_checkpointing=True</strong> , but it tripled the estimate time for the training to complete an epoch from 18 hours to 64 hours. The training cost gonna be at least $153 instead of $43 per epoch. So I discarded it.</li><li>I’ve adjusted <strong>save_steps=10 </strong>to checkpoint every 10 steps as I can terminate the trainer to adjust any parameter is needed to or in case of crash losing 10 steps instead of 100 is cheaper.</li><li><strong>save_total_limit=5 </strong>ensure only the last 5 checkpoint is kept. Actually you can keep is down to 2 only. Just be mindfull about storage here, for this model each checkpoint is about 9 GB, 5 of these will be 45GB of volume storage utilised.</li><li><strong>weight_decay = 0.05 , gradient_accumulation_steps=2, num_generations=8</strong> , these parameters are tuned down to reduce the memory footprint. The OOM no longer an issue with these params and the time per step return to ~20 hours-ish. However whether it’s the optimal memory/cpu tradeoff I didn’t test out. It’s purely intuition.</li><li><strong>trainer.train(resume_from_checkpoint=True)</strong> this option allow us to load the weight from the latest checkpoint, in case you stop the training.</li></ul><p>8. Change the current working directory to workspace, login the <a href="https://wandb.ai/">wandb</a> (you can choose to save the logs into wandb account instead of yours but I highly recommend to use yours) and run the trainer from the terminal:</p><pre>cd /workspace<br>mkdir outputs<br>wandb login<br>python trainer.py</pre><p>After setting up the environment and initiating the training, you should see output displaying progress statistics. For example, on the following screenshot after three hours of training, the progress bar indicated approximately 15 more hours needed to complete all 3,736 steps in one epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQg_JMn2o7RVo1lA9kjxHw.png" /></figure><p>You can track training metric that sent into wandb in realtime, I can also make decision to stop the training and making adjustment to the hyperparameter if metrics trend in undesired direction. In our case, since we store up to 5 checkpoints we can halt training and restart from earlier checkpoints prior to the issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AfoanKYiXf3Ov-zlb3uVQ.png" /></figure><p>In my case, given budget constraints, I opted to stop training before completing a full epoch, specifically I stopped after 820 steps.</p><h4>Test the model</h4><p>I created a Colab notebook to compare outputs between the original and fine-tuned models. The complete code is available here: <a href="https://colab.research.google.com/drive/196Ggt9xWBmRRCRO-QHDUHzcnjGm8e33a?usp=sharing">https://colab.research.google.com/drive/196Ggt9xWBmRRCRO-QHDUHzcnjGm8e33a?usp=sharing</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTqZniPZ9MB-v8vCuTOWYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*alWREBBGBr0OSje7RsCsOQ.png" /></figure><p>Results Analysis</p><p>The fine-tuned model demonstrated an ability to follow instructions but fell short in developing sophisticated logical thinking. Both models failed the famous Strawberry test, with the only notable difference being that the fine-tuned model successfully formatted its answer according to the specified requirements of returning the answer with</p><p>&lt;reasoning&gt; .. &lt;/reasoning&gt; &lt;answer&gt;…&lt;/answer&gt;</p><h4>Conclusion</h4><p>The fine-tuned model did not develop the chain-of-thought (CoT) reasoning I had hoped for, particularly when compared to the self-thinking and verification behavior exhibited by DeepSeek R1. However, considering the model’s relatively small size (1.5B parameters) and limited compute budget (&lt;$15, excluding failed attempts), the absence of sophisticated self-thinking and verification capabilities is understandable. For comparison, TinyZero, which demonstrates these capabilities, uses 3B parameters.</p><p><strong>TinyZero output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GLus9WDc0kxhz9C4" /></figure><p><strong>DeepSeek-R1-Distill-Qwen-1.5B</strong> <strong>output:</strong></p><p>Colab notebook to run the model: <a href="https://colab.research.google.com/drive/1cGcuGLi7orw4BUFl2biJLly4dnc48Hke?usp=sharing">DeepSeek-R1-Distill-Qwen-1.5B</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SO-uBbmN994CBwGbjqYr_w.png" /></figure><p>In retrospect, training CoT models proved less novel than initially anticipated, with the underlying concept closely aligned with other RLHF approaches. This experiment has provided valuable insights into the practical challenges and resource requirements of training language models, even at a smaller scale.</p><h4>TODO</h4><p>These are just my wish list to investigate the solution further:</p><ul><li>Finetune the Qwen 1.5B instruct model to return the &lt;think&gt;..&lt;/think&gt; by default without having to specify it from the prompt.</li><li>Further fine-tune the above model for improvement in reasoning with same approach described in this article.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d1eae3a3aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading MySQL Binlog with Python]]></title>
            <link>https://medium.com/@mahadir.ahmad/reading-mysql-binlog-with-python-c85a8ece3b28?source=rss-f8a461eb6548------2</link>
            <guid isPermaLink="false">https://medium.com/p/c85a8ece3b28</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mahadir Ahmad]]></dc:creator>
            <pubDate>Sun, 23 Jan 2022 06:01:57 GMT</pubDate>
            <atom:updated>2022-01-23T06:01:57.099Z</atom:updated>
            <content:encoded><![CDATA[<p>As a data engineer that manage the company data warehouse I was tasked to ensure data replication reliability from our primary database which is currently a MySQL database into a secondary data storage that is Hadoop (HDFS) compatible for running analytical queries and also all the heavy data processing used by Data Science team.</p><p>During the early days we mainly use custom Python scripts that read the timestamp or primary id for every tables and replicate the new or modified records based on either full-load or incremental. But as the number of table in the database growing and the data team has virtually no control over the backend’s engineer for ensuring the timestamps are updated accordingly, therefore it has become increasingly challenging for me to hit the desired reliability metrics.</p><p>This type of problem is known and classified as under <a href="https://en.wikipedia.org/wiki/Change_data_capture">Change Data Capture</a> (CDC). Luckily for MySQL we already have the solution for that by using the binary log used for the case of server to slave replication, the official manual has a pretty good <a href="https://dev.mysql.com/doc/internals/en/binary-log.html">documentation</a> on that.</p><p>By right you might have guessed this is rather a more broad topic than just bunch of Python codes, and you’re right. I was learning about the low level details about the binlog and dissecting the <a href="https://github.com/noplay/python-mysql-replication">Python MySQL Replication</a> package for diagnosing an error that I couldn’t find the solution anywhere else. This is more like a note for me to refer to in the future and I believe would be useful to the those that might have encountered a similar situation.</p><blockquote>The error: ValueError: Json type 96 is not handled</blockquote><p>And the full stack trace that I produced in my local development environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89c8eefdeaa63fbcc80b0c5b2d4841d9/href">https://medium.com/media/89c8eefdeaa63fbcc80b0c5b2d4841d9/href</a></iframe><p>Before we go futher into the codes, I would like to share the high level architectural design of the system. It’s kind of unconventional, from simple Google search you might find Debezium and Kafka is more well known for solving for this type problem. Although during the exploration stage I had chosen Debezium and AWS Data Management System (DMS) as part of the systems for evaluation, I find that Debezium introduced lots of more unnecessary complexities for my use case while for DMS, it crashed after just about 8 hours of running despite of already used high end ec2 specs, therefore I assume DMS might not be good candidate to scale well for my use case. My third attempt was using pretty ordinary virtual machine specs (with only 2 vcpu core, 2GB RAM and 20GB storage) and I was able to perform almost a real-time data replication to the HDFS (at the time of this writing, we have a peak at 1500+ of changes per second stream to Kinesis) and about 400+ tables in total.</p><figure><img alt="High Level Architecture of the replication process" src="https://cdn-images-1.medium.com/max/814/1*aFX2ROpvFJDB0Gu2KTaJ_A.png" /></figure><p>Okay enough talking let’s now delve into the main topic. To follow along for this tutorial I’ve provided a sample of database import script here that taken from <a href="https://www.digitalocean.com/community/tutorials/working-with-json-in-mysql">Digital Ocean page</a>. and the exported binary log file that we going to primarily use throughout the rest of the content.</p><ul><li><a href="https://gist.github.com/mahadirz/86ec2bb6f9ce52124b1baef0f563c487/raw/92a16271c91f8fb7b5ad3203a035f28a74d0131a/database_import.sql">SQL import file</a></li><li><a href="https://gist.github.com/mahadirz/86ec2bb6f9ce52124b1baef0f563c487/raw/92a16271c91f8fb7b5ad3203a035f28a74d0131a/mysql-bin-changelog.000050.bin">mysql-bin-changelog.000050.bin</a></li><li><a href="https://gist.github.com/mahadirz/86ec2bb6f9ce52124b1baef0f563c487/raw/92a16271c91f8fb7b5ad3203a035f28a74d0131a/mysql-bin-changelog.000052.bin">mysql-bin-changelog.000052.bin</a></li></ul><p>For the purpose of the article, I’m using MySQL v5.7.36 and Python v3.6 but if you’re running a different version than above, do let me know if you have experience unexpected errors or behaviours.</p><p>The installation and configuring the server for the binlog is out of scope here but you may refer to AWS documentation if you’re planning to use RDS.<strong>Installation of the MySQL is optional to follow along . Ensure the server binlog is configured with row based instead of the default mixed-mode.</strong></p><h3>MySQL Binlog Utility</h3><p>When dealing with the MySQL binary log, it’s best for us to know how to use the utility provided by the developer to cross reference or check the output, you can always try to find what’s the content decoded from this utility and start diagnosing from there.</p><p>For the first part of this article, we will dump the log file into a file so that it’s easier and faster to play around. Note that the following photos and snippets are taken from a different database, hence some parameters may be different than from what you noticed from the file I provided above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ec741f3094cf57961cba0811c927dd9/href">https://medium.com/media/6ec741f3094cf57961cba0811c927dd9/href</a></iframe><p>Depending where you installed the database, change the host and read-from-remote server parameters accordingly. In my case, I was using the AWS RDS. This will read the binary log file named <strong>mysql-bin-changelog.009964 </strong>and write the raw value into the file named <strong>mysql-bin-changelog.009964</strong></p><p>You may find the list of the log file by issuing SQL statement</p><blockquote>Show Binary Logs;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*tN-E2qSsdEKuuFAslEI5Uw.png" /></figure><p>The file size displayed from the output of the above statement correspond to the size of the file in bytes as well as the file_position. For instance the 46437018 of mysql-bin-changelog.011677 is the last position in the file.</p><p>You may also use the mysqlbinlog to read existing raw file and decode the values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f50e75223ac9556e5192ad4319075da0/href">https://medium.com/media/f50e75223ac9556e5192ad4319075da0/href</a></iframe><h3>Read the raw file with Python</h3><p>If you inspect the exported binary raw file you might have noticed that the content is gibberish, this is a binary file that has some structures defined by the developer.</p><p>To read the file we can use open() function with rb flag to read in binary mode. The next step that we have to do is to verify the file that we’re dealing with is in fact a binlog. To do this we depend on <a href="https://en.wikipedia.org/wiki/Magic_number_(programming)">Magic Number</a>. The magic number for MySQL binlog is the first 4 bytes containing 0xfe, 0x62, 0x69, 0x6e or 0xfe + bin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*-QMfZl9DYsUsO8sIVB1KqQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76e8a3b9fa9ba0a19a2e7f36ecde20ac/href">https://medium.com/media/76e8a3b9fa9ba0a19a2e7f36ecde20ac/href</a></iframe><p>Moving on, the next part of the file will be the actual event. The event has a header and a body (event data).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNctc_hiz4Jz6o0S2hUrAQ.png" /></figure><p>Referring to the above format, we know that event header is 19 in length (4+1+4+4+4+2), we can then proceed to read 19 bytes.</p><blockquote>header = f.read(19)</blockquote><p>To decode the bytes content we use the <a href="https://docs.python.org/3/library/struct.html">Python Struct</a>.</p><h3>Struct</h3><p>The binary file is written by using C language, in C there is a Struct data type which can be persisted into file. Since Python is not a strong typed language, the decoding of the struct will be a bit unique. Observe the following example for a struct data type that grouped 4 variables of 2 integers and 2 characters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86beb9ebc1376fbf6e97b9aa8afa6275/href">https://medium.com/media/86beb9ebc1376fbf6e97b9aa8afa6275/href</a></iframe><p>If we compile and run the above program, a file <strong>person.bin</strong> is created, on the line 39 we opened the file for reading. I’ve included the screenshot of the output below. On the line 47 and 48, the <strong>sizeof</strong> operator can tell the number of byte to read based on the size of the struct. However if we know the data type for each of the variables we could manually compute the size as well in this case the struct consisted of two 4 byte and two 32 byte (4+4+32+32 = 72).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*uTyHftosVci7pWHOwqJJHw.png" /></figure><p>In Python you can do the same for reading the <strong>person.bin</strong></p><p>From the <a href="https://docs.python.org/3/library/struct.html">Struct documentation</a>. We know the first two are integers or <strong>I</strong> (the size of unsigned and signed is 4, the only different is unsigned exclude negative numbers). The next two are characters (char) with the size of 32 byte each, hence we can specify the format as <strong>32s</strong>. Overall, the format should be as follows</p><pre>unpacked = struct.unpack(&#39;&lt;II32s32s&#39;, data)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/830a9bf2876bfc58c8725014aac7b081/href">https://medium.com/media/830a9bf2876bfc58c8725014aac7b081/href</a></iframe><p>At this point, I believe you’ve got the idea to unpack the 19 bytes of the event header based on the <strong>v4 format description event </strong>.</p><blockquote>struct.unpack(‘&lt;IBIIIH’, header)</blockquote><p>The full source code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ab338d534fdf0f3069845957396ca54/href">https://medium.com/media/8ab338d534fdf0f3069845957396ca54/href</a></iframe><p>And the output:</p><blockquote>timestamp:1641740401<br>event_type:15<br>server_id: 841029529<br>event_size: 119<br>next_log_pos: 123<br>body size 100<br>binlog version 4<br>server version 5.7.36-log<br>timestamp 0</blockquote><p>From line 1–33, we decode the header of the event. From the decoded header, we can know the exact size of its body, in this case the event size is 119 therefore the body is 100 bytes.</p><p>Another important aspect of the header is to tell the type of the event, in this case it’s 15. Referring to this <a href="https://dev.mysql.com/doc/internals/en/event-classes-and-types.html">page</a>, 15 is a <strong>FORMAT_DESCRIPTION_EVENT</strong>. To decode the the event’s body, you must know the structure for each and every type of the event. From the source code above I’ve included from line 35–42 for decoding the data for this event.</p><p>Moving on to the next event, the pointer of the file is at position 123. Decoding the header will tell that it’s an event type 35, which is a <strong>PREVIOUS_GTIDS_LOG_EVENT</strong>. Looking the event data from mysqlbinlog utility command reveal an empty value for the body. Since this event is not directly impacting my use case I just skip it for now.</p><p>Let’s do one more decoding exercise before we conclude this article. We will skip to position 462 that contained a <strong>QUERY_EVENT</strong> type. I’ve refactored the above code to be more reusable for parsing the header.</p><p>To skip into an arbitrary position we can ask file descriptor to move its cursor by calling seek.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/971122c69b45f3abfcd2588d43e2a372/href">https://medium.com/media/971122c69b45f3abfcd2588d43e2a372/href</a></iframe><p>Parsing the Query event body is more tedious than previous event, we need to heavily depends on <a href="https://dev.mysql.com/doc/internals/en/query-event.html">documentation</a> of the event and the <a href="https://github.com/mysql/mysql-server/blob/5.7/libbinlogevents/src/statement_events.cpp">MySQL source code</a> might help as well to understand the mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fVmhOT6ldn1CsaN2Jf0j9Q.png" /></figure><p>The first part of the body is the Post-header. We shall able to decode it by reading 13 bytes and unpack it.</p><pre>post_header = f.read(13)<br>unpacked = struct.unpack(&#39;&lt;IIBHH&#39;, post_header)<br>&quot;&quot;&quot;<br>uint32_t thread_id;<br>uint32_t query_exec_time;<br>size_t db_len;<br>uint16_t error_code;<br>uint16_t status_vars_len;<br>&quot;&quot;&quot;<br>print(f&quot;thread_id : {unpacked[0]} &quot;<br>      f&quot;query_exec_time: {unpacked[1]} &quot;<br>      f&quot;db_len: {unpacked[2]} &quot;<br>      f&quot;error_code: {unpacked[3]} &quot;<br>      f&quot;status_vars_len: {unpacked[4]} &quot;<br>      f&quot;&quot;)</pre><p>Moving to Payload, it consisted of 4 sections. The first one is status-vars which is sort of key-value pair. The key is a 1 byte and followed by value which have size of dependent of the type of the key.</p><p>If you peek into the <a href="https://github.com/mysql/mysql-server/blob/5.7/libbinlogevents/src/statement_events.cpp#L211">source code</a> in github, you can see the switch statement that handle the value. I’ve included the screenshot below for reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWRZydJMy5KiPL2WmzzwbA.png" /></figure><p>We will do the same but very specific to this event only instead of a general purpose parser like in the screenshot above to demonstrate the mechanism, so pardon me for the breaking the DRY principle and lots of hard coded values.</p><p>The second section is the schema, the length used for reading is from the db_len of the Post-Header. In this case the length of the schema is 11. We can optionally unpack by using <strong>&lt;11s</strong> as the format but I skip it because it’s already in ASCII. If you notice here the schema is my_database but the schema from the status-vars is e_store. The reason is my_database is from the statement</p><blockquote>Use my_database;</blockquote><p>While the actual DDL statement refer to e_store.brands.</p><p>The third section is a 1 byte 00 for separator to the query section.</p><p>The fourth and last section is the actual query. I use the formula of <strong>next_log_position-current_log_position-4</strong> to get the size of the query.</p><p>The last 4 byte is the checksum of the event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/941382b794f595deec5cbff3075bcccf/href">https://medium.com/media/941382b794f595deec5cbff3075bcccf/href</a></iframe><p>Running the above code will print the following output in the terminal, which is the DDL statement that created the table brands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*R5aH6qZ65x5fuVjFmZQPJw.png" /></figure><h3>Python MySQL Replication Package</h3><p>I know at this point you may already curious to know if we can skip all these manual works of decoding the data it would be nice if someone already done it for us. Fortunately we can tap into <a href="https://github.com/noplay/python-mysql-replication">Python MySQL Replication</a> which I already mentioned earlier during the introduction.</p><p>However the package is built to read the packet directly from the server, therefore we must convert the binary string into packet first.</p><pre>from pymysql.protocol import MysqlPacket<br>packet = MysqlPacket(struct.pack(&quot;&lt;c&quot;, b&#39;0&#39;) + header + body, &#39;utf&#39;)</pre><p>After that, we can pass this packet into the BinLogPacketWrapper which will do the heavy lifting of parsing the logs.</p><pre>from pymysqlreplication.packet import BinLogPacketWrapper<br>binlog_event = BinLogPacketWrapper(packet, table_map,<br>                                   connection,<br>                                   True,<br>                                   allowed_events,<br>                                   None,<br>                                   None,<br>                                   None,<br>                                   None,<br>                                   False,<br>                                   False<br>                                   )</pre><p>The following is the fully working example of using the package for reading binary log file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e922ddec931b17f84140d6cbd8b082e/href">https://medium.com/media/6e922ddec931b17f84140d6cbd8b082e/href</a></iframe><p>If you reached to this point, congratulations. I didn’t plan to have the article this long, there are so much more to cover, I was planning to include debugging the error that I encountered but decided to drop it last minute. Having the capability to parse the log locally after dumping the log into file is already sufficient to replay and debug any errors that you might encounter while maintaining (or developing) the replication process.</p><p>In the next article I’ll try to cover either the CDC part, or our recent custom Pyspark ORM for more productive analytical query and data documentation.</p><p>If you found this article useful, please hit that clap button 👏 and follow me to get more articles and tutorials on your feed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c85a8ece3b28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to parse billion of User Agents [using Pyspark]]]></title>
            <link>https://medium.com/@mahadir.ahmad/how-to-parse-billion-of-user-agents-using-pyspark-f57e680727e7?source=rss-f8a461eb6548------2</link>
            <guid isPermaLink="false">https://medium.com/p/f57e680727e7</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[emr]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Mahadir Ahmad]]></dc:creator>
            <pubDate>Sun, 03 Nov 2019 14:21:30 GMT</pubDate>
            <atom:updated>2019-11-05T04:21:52.901Z</atom:updated>
            <content:encoded><![CDATA[<p>When your organization practice collecting (almost) everything first and (do) process it later, it has to be a time when you need to analyze records that has been sitting in storage for a prolonged time. The size of the records could reach multi-terabytes with billion of entries. This is when the traditional approach of data processing is at its limit.</p><p>Recently I need to analyze a considerably huge clickstream data with the queries related to device and browser. As a python developer my first step is to locate package that can parse <strong><em>user agent</em></strong> from the clickstream and returns the device, OS, browser and related information. I found the right package that can do the job with this library: <a href="https://github.com/selwin/python-user-agents">Python User Agent</a>.</p><p>The next step is I want to find out how fast this package can parse the <strong><em>user agents</em></strong> so I can estimate the time if I were to run it on a billion records. I use Jupyter to prototype my steps (This run in EC2 ml.t2.large should it matters). With 10k sample combined with <strong><em>timeit</em></strong> magic I can roughly get the average iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hmsfj-aHlzKCtFH334kYTg.png" /></figure><p>The average iterations per second is 699.30 but I’ll round it to 700. Let’s do a quick maths here if I were to parse a billion entries:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdd8a1558a976055eb715c5fcb4a871f/href">https://medium.com/media/fdd8a1558a976055eb715c5fcb4a871f/href</a></iframe><p>I probably required to have 49 parallel execution to complete the parsing within 8 hours. That’s only part of the story, I also need to code for scheduler and do the testing for reliability. Give or take, might cost me few days to finally see the result. Using existing tool that can solve this problem would be much more desirable.</p><h3>Apache Spark</h3><p>Fortunately, we can accomplish this task without sweating by using Apache Spark. In AWS apache Spark can be found in ElasticMapReduce (EMR) service. You can spin on demand cluster from EMR and accomplish the distributed computation requirements without the need to build anything from scratch. For cluster configuration, we can use <strong>Task Node </strong>only (we’ll use s3 as HDFS storage). If this is a repeating operation you can utilize the<strong> steps options</strong> when launching the cluster to automatically run the script and terminate once completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUzbfiUk6qTSMQL9pL3GRQ.png" /></figure><p>But for our case, we will be using a quick way to submit our pyspark parsing application (let’s call this <strong><em>ETL</em></strong> job) through <strong><em>sparks-submit</em></strong> cli and some munging with zeppelin notebook.</p><p>Before we code our ETL, let’s take a step back, could it be other way to optimize our job? Parsing the user agent is a costly operation but join operation relatively isn’t, if we can parse only unique user agent and perform a <em>join operation separately, </em>would it be faster?. Let’s find out the total unique entries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMqw6uX9y2sXX4K_mEc24g.png" /></figure><p>Wow, only 8M unique records out of 1B or roughly 0.9%. We could theoretically speed up the process by 115X. If you notice from Zeppelin notebook above the data is already partitioned and in parquet format. By partitioning with right numbers and read from columnar storage, this will naturally help speed up operation as well. We’ll touch about partitioning later in this article but if you’re interested to learn more I highly recommend this <a href="https://medium.com/parrot-prediction/partitioning-in-apache-spark-8134ad840b0">partitioning in apache spark</a>.</p><p>Now, we’re going to prepare the unique user agent into a new file to make our ETL jobs faster by directly reads from parquet . Notice that I also include the count aggregation, it might be handy we somehow decided to filter only user agent having certain count threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7bqmcK8VuafZ_4CvPVa0w.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe2de136de67f4c3dfb37588532126c/href">https://medium.com/media/3fe2de136de67f4c3dfb37588532126c/href</a></iframe><p>The descriptive statistics from count above shows half of the entries has occurence below 2. Depending on the scenario, you may want to filter out entries less than or equal to 2 or at extreme anything less than 844. Doing so can effectively reduce the total entry to be parsed by twice or 100X respectively. But for the sake of this article which clearly stated 1B user agents, I’ll leave the data as it is otherwise the final result will not add up to 1B right?</p><h3>Pyspark UDF</h3><p>Now that we’ve optimized our operation, let’s quickly prototype simple user agent parser from Zeppelin notebook. In order to do so we need to understand the concept of Pyspark function or UDF. I highly recommend you to read through this <a href="https://changhsinlee.com/pyspark-udf/">article</a> and understand the concept first before proceed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1a9d39dc52b6f8b156379b63a7cd454/href">https://medium.com/media/c1a9d39dc52b6f8b156379b63a7cd454/href</a></iframe><p>Copy our prototype of ETL script above into EMR Master server (SSH into it):</p><blockquote>$ ssh emr<br>$ nano test.py<br>$ spark-submit test.py</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgIE2R0FH-NG4yGGdXUtmw.png" /></figure><p>Opps! We encountered ‘user_agents’ module not found error. The reason is we haven’t install the package before executing the submit. You might be thinking by now how to install the parser package on our cluster, imagine if the cluster has 10 task nodes, do we need to login to each and every server and execute <strong><em>pip install</em></strong>?. The answer is Yes and No, both were possible to solve the dependencies, but the elegant way is we can zip pip modules into a file and submit together with our ETL script. Remember the Task Node we configured with spot instance? At any time, AWS might shut it down and therefore the first option were not something we should go after.</p><blockquote># Let’s package our module into a zip file<br>$ pip-3.6 install pyyaml ua-parser user-agents -t dependencies<br>$ cd dependencies<br>$ zip -r ../dependencies.zip .<br>$ cd ..<br># you may choose to move this file to s3 if you need to submit job via livy<br># optional<br># aws s3 cp dependencies.zip s3://involve-data-science/emr/dependencies.zip</blockquote><p>With <strong>py-files</strong> option we can now submit the pyspark script and its dependencies.</p><blockquote>$ spark-submit — py-files dependencies.zip test.py</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFjuMarPKNhdVCHVvUwzeA.png" /></figure><p>By now, it should be pretty much straight forward to code our final ETL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa709e72c07c5d9f123364e4ec314dbf/href">https://medium.com/media/aa709e72c07c5d9f123364e4ec314dbf/href</a></iframe><p>The only part I want to comment is the repartition. If you still remember the number of partition for the unique user agent dataframe is 25. I actually tried with this default number and I notice only 8 executors were used. But with 36 vcores I can theoretically distribute to at least 36 executors. Hence, I used 3x multiplier to make the new partition size to 108. Practically, from the test I ran this decreased the time to complete the task from 56 minutes to only 31 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNzhkoSIFq8zCga9F8YHRg.png" /></figure><p>At this stage, you’ll have a lookup file and can perform join operation with any pyspark dataframe that have user agent column with minimal cost. For sake of completeness I’ll demonstrate an example to join it with sales data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRngwbYDSeJlc9TTySAPPg.png" /></figure><p>With 5M sales records joining to our lookup dataframe and perform filtering of mobile device and amount aggregation only took 47 seconds. You can now inform the business department the top mobile Operating System (OS) is Android with RM 3B of sales followed by iOS.</p><p>We can do so much more analysis using this lookup, however if you’re a data engineer you may now pass the next stage to data analyst / data scientist.</p><h3>Cost Analysis</h3><p>Congratulation if you manage to read until here, for final part I think it’s not complete without cost calculation. Let’s do some quick estimation how much I’ve spent in AWS, after all we’ll need to explain whether by reducing the time from 16 days to couple of hours were justified.</p><p>In term of cost we only use S3 for HDFS storage and EMR. For storage, I’ve transformed original data of 1B ~ 1TB into a gzip compressed parquet files with new size of 180GB.</p><p>All the tasks above should be completed within 3 hours but worse case it may takes longer when we take into account testing and time spent for troubleshooting, so just adding it up to 8 hours which is common office working hour.</p><p>The cost structure for EMR can be found <a href="https://aws.amazon.com/emr/pricing/">here</a>. As for spot instance the price was $0.0654 per hour for m5.xlarge.</p><blockquote>($0.048 * 10 * 8) + ($0.24 * 1 * 8) + ($0.0654 * 9 * 8) = $10.47</blockquote><p>As for s3 I will round up to 200GB to take into account new files that were created to store the lookup and probably some failed testing. The pricing can be found <a href="https://aws.amazon.com/s3/pricing/">here</a>. To calculate the usage for 8 hours we need to convert to <a href="https://aws.amazon.com/s3/faqs/#How_will_I_be_charged_and_billed_for_my_use_of_Amazon_S3">GB-Month</a>.</p><blockquote>200*1024*1024*1024*8/1073741824/744 = 2.15<br>2.15 * $0.024 = $0.05</blockquote><p>Overall our cost should be no higher than $10.52 (0.05 + 10.47). By taking the optimistic estimation of 3 hours the cost down to only $3.95 or RM 16.20.</p><p>All price calculations are based on Singapore region. I’ve prepared the <a href="https://docs.google.com/spreadsheets/d/1HMWL1OdvqB-mTfVctMklciHCrC5Z7aecUmPnFmK5u_4/edit?usp=sharing">spreadsheet</a> for you to play around with the hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_hDrEGGjFNDKaeMNlKGSw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f57e680727e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>