<?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 Tuyentst on Medium]]></title>
        <description><![CDATA[Stories by Tuyentst on Medium]]></description>
        <link>https://medium.com/@tuyen66tst?source=rss-03b80696e5bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*z_vkFuuPWFvH7Rmh</url>
            <title>Stories by Tuyentst on Medium</title>
            <link>https://medium.com/@tuyen66tst?source=rss-03b80696e5bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:45:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tuyen66tst/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[Tryhard Firewall]]></title>
            <link>https://medium.com/@tuyen66tst/tryhard-firewall-6c9af4281805?source=rss-03b80696e5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c9af4281805</guid>
            <dc:creator><![CDATA[Tuyentst]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 16:24:04 GMT</pubDate>
            <atom:updated>2025-07-20T16:24:04.370Z</atom:updated>
            <content:encoded><![CDATA[<p>Netfilter Firewall Mechanisms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*GnFrwk6mZNblXi_J8iptKA.png" /></figure><p>The image above is filter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBnirYpRAzsj1virvBg4GA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDIZrOoWKvBkxyO5TC48Qw.png" /></figure><p>iptables</p><p>Syntax:</p><pre>iptables -A INPUT -p icmp -s source address -d destinate address --dport 22 -j DROP<br></pre><pre>iptables -t &lt;table&gt; &lt;option&gt; &lt;chain&gt; &lt;matching criteria&gt; -j &lt;target&gt;</pre><p>mặc định tables đang là filter</p><p>option -A, -I, -D, -R</p><p>D delete</p><p>R replace</p><p>F xóa toàn bộ rule</p><p>X xóa chain do người dùng chọn</p><p>tables</p><p>filter INPUT, OUTPUT, FORWARD</p><p>nat OUPUT, PREROUTING, POSTROUTING</p><p>mangle INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING</p><p>raw PREROUTING, OUTPUT</p><pre>&lt;matching criteria&gt; any way</pre><p>nftables</p><pre>nft &lt;command&gt; &lt;subcommand&gt; &lt;chain&gt; &lt;rule definition&gt;</pre><p>command (add, list, insert, delete, flush)</p><p>subcommand(table, chain, rule)</p><p>tức là để cấu hình một rule như iptable (iptables -t filter -A INPUT -p tcp — dport 22 -j ACCEPT) thì nftables sẽ tách riêng ra</p><pre>nft add table ip filter <br>nft add chain ip filter input { type filter hook input priority 0 \n}<br>nft add rule ip filter input tcp dport 22 accept </pre><p>bắt buộc phải có {type filter hook input priority 0 \n}</p><p>và 0 có thể tinh chỉnh nếu -100 chạy trước 0 và 100 chạy sau cùng</p><p>Câu hỏi ngu một chút tại sao lúc sử dụng filter và lúc thì sử dụng mangle ?</p><p>filter dùng để cho hay không cho (Dùng để “cho hay không”) (dùng khi bạn muốn <strong>chặn/cho phép</strong> gói tin (firewall logic))</p><p>mangle dùng để phẫu thuật</p><p>thay đổi ttl, DSCP, TOS, ĐÁNH DẤU GÓI , DROP GÓI SỚM TRƯỚC KHI XỬ LÝ CONNTRACK</p><p>conntrack là theo dõi kết nối cho phép ghi nhớ trạng thái của kết nối mạng (TCP, UDP,ICMP,…) nhằm phân biệt trạng thái của gói tin</p><p>— ctstate NEW gói bắt đầu một kết nối mới</p><p>ESTABLISHED gói thuộc về một kết nối đã được thiết lập</p><p>RELATED gói liên quan đến kết nối đã có</p><p>INVALID gói không khớp với bất kỳ kết nối nào đã biết hoặc có lỗi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hI8c9AJWlMoDJlhzRqgRA.png" /></figure><p>Initializing the Firewall</p><p>Symbolic Constants Used in the Firewall Examples</p><p>kiểu khai báo hằng số cục bộ sao cho chuyên nghiệp</p><pre> #!/bin/sh<br> INTERNET=&quot;eth0&quot;                      # Internet-connected interface<br> LOOPBACK_INTERFACE=&quot;lo&quot;              # However your system names it<br> IPADDR=&quot;my.ip.address&quot;               # Your IP address<br> MY_ISP=&quot;my.isp.address.range&quot;        # ISP server &amp; NOC address range<br> SUBNET_BASE=&quot;my.subnet.network&quot;      # Your subnet&#39;s network address<br> SUBNET_BROADCAST=&quot;my.subnet.bcast&quot;   # Your subnet&#39;s broadcast address<br> LOOPBACK=&quot;127.0.0.0/8&quot;               # Reserved loopback address range<br> CLASS_A=&quot;10.0.0.0/8&quot;                 # Class A private networks<br> CLASS_B=&quot;172.16.0.0/12&quot;              # Class B private networks<br> CLASS_C=&quot;192.168.0.0/16&quot;             # Class C private networks<br> CLASS_D_MULTICAST=&quot;224.0.0.0/4&quot;      # Class D multicast addresses<br> CLASS_E_RESERVED_NET=&quot;240.0.0.0/5&quot;   # Class E reserved addresses<br> BROADCAST_SRC=&quot;0.0.0.0&quot;              # Broadcast source address<br> BROADCAST_DEST=&quot;255.255.255.255&quot;     # Broadcast destination address<br> PRIVPORTS=&quot;0:1023&quot;                   # Well-known, privileged port range<br> UNPRIVPORTS=&quot;1024:65535&quot;             # Unprivileged port range</pre><p>Enabling Kernel-Monitoring Support</p><p><strong>Mục đích bảo vệ</strong> <strong>Lệnh cấu hình</strong> <strong>Ý nghĩa</strong></p><p>🛡️ <strong>Chặn ping broadcast</strong> echo 1 &gt; /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts Ngăn ICMP echo (ping) tới địa chỉ broadcast hoặc multicast – chống Smurf attack.</p><p>❌ <strong>Tắt source routing</strong> echo 0 &gt; /proc/sys/net/ipv4/conf/all/accept_source_route Chặn gói IP có định tuyến nguồn – loại tấn công cũ không còn hợp lệ.</p><p>🔄 <strong>Bật TCP SYN cookies</strong> echo 1 &gt; /proc/sys/net/ipv4/tcp_syncookies Bảo vệ khỏi tấn công SYN flood bằng kỹ thuật cookies thay vì giữ state.</p><p>🚫 <strong>Tắt nhận ICMP redirect</strong> echo 0 &gt; /proc/sys/net/ipv4/conf/all/accept_redirects Ngăn host bị router dụ sang route giả mạo.</p><p>🚫 <strong>Tắt gửi ICMP redirect</strong> echo 0 &gt; /proc/sys/net/ipv4/conf/all/send_redirects Host không gửi ICMP redirect – vì chỉ router mới nên làm.</p><p>🧠 <strong>Bật </strong><strong>rp_filter (Reverse Path Filter)</strong></p><p>sử dụng kernel (Trong môi trường WebOS / Automotive <strong>nơi tài nguyên hạn chế</strong>, bạn <strong>nên ưu tiên dùng các thiết lập kernel (</strong><strong>/proc/sys/net/...) hơn là iptables/nftables</strong> nếu mục tiêu là:)</p><pre># Vô hiệu hóa ICMP redirect, source routing, spoofing...<br>echo 0 &gt; /proc/sys/net/ipv4/conf/all/accept_redirects<br>echo 0 &gt; /proc/sys/net/ipv4/conf/all/send_redirects<br>echo 0 &gt; /proc/sys/net/ipv4/conf/all/accept_source_route<br>echo 1 &gt; /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts<br>echo 1 &gt; /proc/sys/net/ipv4/tcp_syncookies<br>echo 1 &gt; /proc/sys/net/ipv4/conf/all/log_martians<br><br># RPF - chống spoofing interface<br>for f in /proc/sys/net/ipv4/conf/*/rp_filter; do<br>  echo 1 &gt; &quot;$f&quot;<br>done</pre><p>Removing Any Preexisting Rules</p><pre># Remove any existing rules from all chains <br>IPT=&quot;/sbin/iptables&quot;<br>IPT --flush<br>IPT -t nat -f<br>IPT -t mangle -f<br>(Xóa tất cả chuỗi do người dùng định nghĩa (user-defined chains):)<br>$IPT -X<br>$IPT -t nat -X<br>$IPT -t mangle -X <br></pre><p>Resetting Default Policies and Stopping the Firewall</p><pre>#!/bin/sh<br><br>### === Biến hệ thống === ### <br>IPT=&quot;/sbin/iptables&quot;<br><br>### === STOP FIREWALL nếu gọi với &#39;stop&#39; === ###<br>### lệnh chạy sh /root/firewall.sh stop<br>if [ &quot;$1&quot; = &quot;stop&quot; ]; then<br>    echo &quot;[!] Stopping firewall completely — ALL TRAFFIC ALLOWED&quot;<br>    $IPT --flush<br>    $IPT -t nat --flush<br>    $IPT -t mangle --flush<br><br>    $IPT -X<br>    $IPT -t nat -X<br>    $IPT -t mangle -X<br><br>    $IPT --policy INPUT   ACCEPT<br>    $IPT --policy OUTPUT  ACCEPT<br>    $IPT --policy FORWARD ACCEPT<br><br>    exit 0<br>fi<br><br>### === FLUSH &amp; RESET CHÍNH SÁCH === ###<br>echo &quot;[*] Flushing all iptables rules and resetting default policies&quot;<br>$IPT --flush<br>$IPT -t nat --flush<br>$IPT -t mangle --flush<br><br>$IPT -X<br>$IPT -t nat -X<br>$IPT -t mangle -X<br><br>$IPT --policy INPUT   DROP<br>$IPT --policy OUTPUT  ACCEPT<br>$IPT --policy FORWARD DROP<br><br>### === CHO PHÉP GIAO TIẾP LOOPBACK === ###<br>echo &quot;[*] Enabling unrestricted loopback traffic&quot;<br>$IPT -A INPUT  -i lo -j ACCEPT<br>$IPT -A OUTPUT -o lo -j ACCEPT</pre><p>Khác nhau giữa DROP VÀ REJECT</p><p>DROP âm thầm loại bỏ gói tin, người gửi ko biết gói tin bị chặn hay mất, chặn hoàn toàn</p><p>REJECT Từ chối và gửi thông báo lỗi về người gửi, người gửi nhận lỗi ngay lập tức, từ chối rõ ràng</p><p>✔️ <strong>DROP là lựa chọn an toàn &amp; chuyên nghiệp hơn</strong> trong môi trường sản phẩm (production).<br> ✔️ <strong>REJECT rất hữu ích khi phát triển, test, hoặc kiểm tra firewall</strong> trong lab/dev.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c9af4281805" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing the 2025 Vietnamese National High School Exam Data Using Vanna AI]]></title>
            <link>https://medium.com/@tuyen66tst/visualizing-the-2025-vietnamese-national-high-school-exam-data-using-vanna-ai-e53ce3967caa?source=rss-03b80696e5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e53ce3967caa</guid>
            <dc:creator><![CDATA[Tuyentst]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 15:51:32 GMT</pubDate>
            <atom:updated>2025-07-17T15:51:32.602Z</atom:updated>
            <content:encoded><![CDATA[<p>How I built a RAG-powered text-to-SQL app without knowing SQL</p><h3>Introduction</h3><p>As someone just beginning to learn about AI, I’m not yet comfortable writing SQL queries from scratch. But I still want to explore and analyze real-world datasets — like the 2025 Vietnamese National High School Exam results — to uncover patterns, generate insights, and even make predictions about university admissions.</p><p>That’s where <strong>Vanna AI</strong> comes in.</p><p>With Vanna AI, I can simply write what I want in natural language (in English or Vietnamese), and it generates the corresponding SQL queries for me. No need to memorize SQL syntax or worry about database joins. This blog walks you through my journey using Vanna AI to build a data analysis pipeline — with the long-term goal of creating a predictive model for university cut-off scores.</p><h3>What is Vanna AI?</h3><p>Vanna AI is an <strong>open-source Text-to-SQL framework</strong> that helps you:</p><ul><li><strong>Translate natural language questions into SQL queries</strong> automatically.</li><li><strong>Connect to your own structured datasets</strong> (like CSVs or databases).</li><li><strong>Use Retrieval-Augmented Generation (RAG)</strong> to improve query accuracy by referencing documentation, schema, and examples.</li><li><strong>Adapt to dynamic datasets</strong>, making it a strong fit for evolving student databases like national exam scores.</li></ul><p>Even better: you don’t need to be a SQL expert. Vanna bridges the gap between what you <em>want to know</em> and what the <em>data actually contains</em>.</p><h3>Motivation Behind This Project</h3><p>While exploring the 2025 Vietnamese National High School Exam dataset (Điểm thi THPT Quốc Gia), I wanted to answer questions like:</p><ul><li>What’s the average Math score across the country?</li><li>Which students scored above 8 in Literature but below 6 in Math?</li><li>What are the top 5 provinces with the highest overall scores?</li></ul><p>But since I wasn’t confident in SQL, I needed a smarter solution. Vanna AI gave me the ability to:</p><p>✅ Ask these questions in natural language<br>✅ Get instant SQL translations<br>✅ Focus on <strong>insights</strong>, not syntax</p><p>Eventually, I aim to build <strong>machine learning models</strong> on top of this, such as predicting university admission cut-offs based on subject scores.</p><h3>How to Get a Free OpenAI API Key for Learning</h3><p><a href="https://medium.com/@tuyen66tst/how-to-obtain-a-free-gpt-api-key-for-basic-learning-de32592ee6d7">References</a></p><h3>Building Vanna AI for a RAG Project with National Exam Data</h3><p><a href="https://www.kaggle.com/code/phctuynl/thpt-2025-sql-with-vanna-ai">References</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e53ce3967caa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Obtain a Free GPT API Key for Basic Learning from Third Party (100% is ok)]]></title>
            <link>https://medium.com/@tuyen66tst/how-to-obtain-a-free-gpt-api-key-for-basic-learning-de32592ee6d7?source=rss-03b80696e5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/de32592ee6d7</guid>
            <dc:creator><![CDATA[Tuyentst]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 15:40:45 GMT</pubDate>
            <atom:updated>2025-07-17T16:11:40.488Z</atom:updated>
            <content:encoded><![CDATA[<p>Using a GPT API key is straightforward, but it typically requires payment for each training token and a payment method like Visa or PayPal. For basic learning purposes, spending money may not be necessary. I’ve discovered a GitHub repository that provides free API keys (supporting models like GPT-4o, DeepSeek, and more). With just a GitHub account, you can get your own API key. Additionally, this repository offers guides on obtaining free keys from third-party sources (you can explore these for more details). Since the GitHub page is in Chinese, which may be challenging to navigate, I’ll provide a step-by-step guide to make the process easy.</p><p><strong>Step-by-Step Guide to Get a Free GPT API Key</strong></p><p>Step 1: Click on this link to visit the <a href="https://github.com/chatanywhere/GPT_API_free?tab=readme-ov-file">GitHub repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4-4aHEglUanabk-8JopWQ.png" /></figure><p>Step 2: Scroll down to the section labeled 🚀申请领取内测免费API Key (Apply for a Free Beta API Key). Click on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*_37NiHkymttjU4O9NK_bTA.png" /></figure><p>Step 3: A new interface will appear displaying your API key in the format sk-…. Copy this key carefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*BM7L2cFlOrc84axvG2mtAw.png" /></figure><p><strong>Step 4</strong>: Since this is a third-party service, the code implementation differs from the official platform. Below is an example of how to use the API key in your code.</p><pre>import openai<br><br>client = openai.OpenAI(api_key=&#39;sk-..&#39;,base_url=&quot;https://api.chatanywhere.tech/v1&quot;)<br>response = client.chat.completions.create(model=&#39;gpt-4o&#39;,<br><br>messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],)</pre><p>With the tool Vanna AI</p><pre>from vanna.openai.openai_chat import OpenAI_Chat<br>from vanna.chromadb.chromadb_vector import ChromaDB_VectorStore<br>import openai<br><br>class MyVanna(ChromaDB_VectorStore, OpenAI_Chat):<br>    def __init__(self, config=None):<br>        config = config or {}<br>        <br>        if &#39;base_url&#39; in config:<br>            openai.api_base = config[&#39;base_url&#39;]<br>        <br>        ChromaDB_VectorStore.__init__(self, config=config)<br>        OpenAI_Chat.__init__(self, config=config)<br>    <br>    def submit_prompt(self, prompt, **kwargs):<br>        if hasattr(self, &#39;client&#39;) and hasattr(self.client, &#39;base_url&#39;):<br>            self.client.base_url = &#39;https://api.chatanywhere.org/v1&#39;<br>        <br>        return super().submit_prompt(prompt, **kwargs)<br><br>vn = MyVanna(config={<br>    &#39;api_key&#39;: &#39;sk-...&#39;,<br>    &#39;model&#39;: &#39;gpt-4o-mini&#39;,<br>    &#39;base_url&#39;: &#39;https://api.chatanywhere.org/v1&#39; <br>})</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de32592ee6d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detail about how to work RASA Chatbot]]></title>
            <link>https://medium.com/@tuyen66tst/detail-about-how-to-work-rasa-chatbot-6b285d8197a7?source=rss-03b80696e5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b285d8197a7</guid>
            <dc:creator><![CDATA[Tuyentst]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 07:15:29 GMT</pubDate>
            <atom:updated>2025-03-22T07:33:03.488Z</atom:updated>
            <content:encoded><![CDATA[<p>Rasa chatbot is …</p><h3>RASA NLU Pipeline</h3><p>Đây là mô hình huấn luyện sẽ huấn luyện sao cho mô hình nó phải huấn luyện đúng dựa trên nhãn thực xem cái này để biết thêm chi tiết</p><p><a href="https://medium.com/the-research-nest/using-the-diet-classifier-for-intent-classification-in-dialogue-489c76e62804">Using the DIET classifier for intent classification in dialogue | by Mohit Saini | The Research Nest | Medium</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sg37-Zu4OY4U_a7IpUCt7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*2PNmrARjw_zpOyqY.png" /></figure><p>DIETClassifier chỉ nằm trong một phần của khối NLU trong Rasa</p><p>Tin nhắn (Message) đi vào RASA NLU, được xử lý đầu vào, trích chọn véc-tơ đặc trưng, áp dụng các bộ trích chọn thực thể (nếu có), xác định ý định của người dùng.<br>Sau khi xác định được ý định, trích chọn được các thực thể trong tin nhắn, dữ liệu được đẩy sang RASA Core (Từ giờ đến cuối bài mình sẽ gọi là Dialog Policies), dữ liệu các ý định và thực thể từ các tin nhắn của bước hội thoại trước cũng được đưa vào mô hình để xử lý và tính toán hành động tiếp theo để đáp lại người dùng.<br>Hãy cùng đi sâu từng thành phần để chúng ta có thể hiểu chi tiết hơn bằng sơ đồ ví dụ trong hình trên.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExBmNO5ksrUP6-VKQpnI6w.png" /></figure><p><strong>Các thành phần cấu tạo nên một hệ thống chatbot RASA hoàn chỉnh<br></strong>Bên cạnh hai thành phần cốt lõi trên, hệ thống chatbot RASA cần thêm các thành phần để xử lý bộ nhớ, kết nối các thành phần lại với nhau để hoạt động hiệu quả</p><p><strong><em>NLU Pipeline</em></strong>: Các module RASA NLU<br><strong><em>Dialog Policies</em></strong>: Các policy của RASA Core<br><strong><em>Action Server</em></strong>: Các action đáp lại người dùng được viết bằng python (action mặc định là action dạng text)<br><strong><em>Tracker Store</em></strong>: Module lưu trữ các slot, entity, câu hội thoại (Đây chính là module bộ nhớ lưu trữ của chatbot)<br><strong><em>Lock Store</em></strong>: Module đảm bảo các câu hội thoại gửi đến chatbot được xử lý tuần tự, không bị race condition<br><strong><em>Filesystem</em></strong>: Module lưu trữ và quản lý các tệp của chatbot<br><strong><em>Agent</em></strong>: Module xử lý chung và kết nối các thành phần khác<br>Trong các thành phần trên, chúng ta chủ yếu làm việc với NLU Pipeline, Dialog Policies, Action Server và sử dụng Tracker để xử lý dữ liệu trong Action Server</p><pre>Dưới đây là các ví dụ minh họa cho từng thành phần trong hệ thống RASA chatbot:  <br><br>---<br><br>### **1. NLU Pipeline**  <br>Đây là pipeline xử lý ngôn ngữ tự nhiên, bao gồm tokenization, entity recognition, intent classification, v.v.  <br>Ví dụ về `config.yml` cho NLU pipeline:<br><br>```yaml<br>language: &quot;en&quot;<br>pipeline:<br>  - name: &quot;WhitespaceTokenizer&quot;<br>  - name: &quot;CountVectorsFeaturizer&quot;<br>  - name: &quot;DIETClassifier&quot;<br>    epochs: 100<br>  - name: &quot;EntitySynonymMapper&quot;<br>  - name: &quot;ResponseSelector&quot;<br>    epochs: 100<br>```<br>Pipeline trên gồm:  <br>✅ **WhitespaceTokenizer**: Tách từ dựa trên khoảng trắng  <br>✅ **CountVectorsFeaturizer**: Trích xuất đặc trưng  <br>✅ **DIETClassifier**: Phân loại intent &amp; nhận diện entity  <br>✅ **EntitySynonymMapper**: Xử lý từ đồng nghĩa  <br>✅ **ResponseSelector**: Chọn phản hồi phù hợp  <br><br>---<br><br>### **2. Dialog Policies**  <br>Chính sách hội thoại quyết định chatbot sẽ phản hồi như thế nào dựa trên ngữ cảnh.  <br><br>Ví dụ về `policies` trong `config.yml`:<br><br>```yaml<br>policies:<br>  - name: MemoizationPolicy<br>  - name: TEDPolicy<br>    max_history: 5<br>    epochs: 100<br>  - name: RulePolicy<br>```<br>✅ **MemoizationPolicy**: Nhớ các hội thoại trước đó và phản hồi dựa trên mẫu hội thoại đã học  <br>✅ **TEDPolicy**: Mô hình học sâu giúp chatbot dự đoán bước tiếp theo  <br>✅ **RulePolicy**: Xử lý các quy tắc cố định, như fallback hoặc chào hỏi  <br><br>---<br><br>### **3. Action Server**  <br>Hệ thống xử lý logic phức tạp bằng Python thay vì chỉ phản hồi văn bản.  <br><br>Ví dụ `actions.py`:<br><br>```python<br>from rasa_sdk import Action<br>from rasa_sdk.events import SlotSet<br><br>class ActionCheckWeather(Action):<br>    def name(self):<br>        return &quot;action_check_weather&quot;<br><br>    def run(self, dispatcher, tracker, domain):<br>        city = tracker.get_slot(&quot;city&quot;)<br>        weather = &quot;sunny&quot;  # Giả lập dữ liệu thời tiết<br>        dispatcher.utter_message(text=f&quot;The weather in {city} is {weather}.&quot;)<br>        return [SlotSet(&quot;weather&quot;, weather)]<br>```<br>✅ **`dispatcher.utter_message()`**: Gửi phản hồi đến người dùng  <br>✅ **`tracker.get_slot(&quot;city&quot;)`**: Lấy dữ liệu từ slot  <br>✅ **`SlotSet(&quot;weather&quot;, weather&quot;)`**: Cập nhật slot  <br><br>---<br><br>### **4. Tracker Store**  <br>Lưu trữ lịch sử hội thoại, slot, entity, intent đã phát hiện.  <br><br>Ví dụ gọi dữ liệu từ tracker trong Action Server:<br><br>```python<br>latest_intent = tracker.latest_message[&#39;intent&#39;].get(&#39;name&#39;)<br>print(f&quot;User&#39;s latest intent: {latest_intent}&quot;)<br>```<br>✅ **Tracker Store** giúp chatbot có trí nhớ về hội thoại trước đó.  <br><br>---<br><br>### **5. Lock Store**  <br>Đảm bảo không có race condition khi nhiều người dùng tương tác cùng lúc.  <br>Sử dụng **Redis** làm Lock Store trong `endpoints.yml`:<br><br>```yaml<br>lock_store:<br>  type: redis<br>  url: localhost<br>  port: 6379<br>  db: 0<br>  password: null<br>```<br>✅ Redis đảm bảo mỗi request được xử lý theo thứ tự.  <br><br>---<br><br>### **6. Filesystem**  <br>Lưu trữ các model, logs, và dữ liệu huấn luyện chatbot.  <br><br>Ví dụ cấu trúc thư mục RASA:  <br>```<br>/my_bot<br>│── data/              # Dữ liệu huấn luyện<br>│── models/            # Lưu model đã train<br>│── actions/           # Chứa action server<br>│── config.yml         # Cấu hình chatbot<br>│── domain.yml         # Định nghĩa intents, entities, responses<br>│── endpoints.yml      # Cấu hình kết nối backend<br>│── credentials.yml    # Cấu hình xác thực API<br>```<br>✅ `models/` chứa mô hình đã huấn luyện  <br><br>---<br><br>### **7. Agent**  <br>Module điều phối chatbot, kết nối các thành phần khác như NLU, policies, tracker, action server.  <br><br>Ví dụ chạy chatbot với `Agent` trong Python:<br><br>```python<br>from rasa.core.agent import Agent<br><br>agent = Agent.load(&quot;models/latest.tar.gz&quot;)<br>response = agent.handle_text(&quot;What&#39;s the weather in New York?&quot;)<br>print(response)<br>```<br>✅ `Agent.load()`: Load model chatbot  <br>✅ `handle_text()`: Xử lý tin nhắn người dùng  <br><br>---<br><br>🔹 **Tóm tắt lại:**  <br>- **NLU Pipeline** → Hiểu ngôn ngữ người dùng  <br>- **Dialog Policies** → Quyết định phản hồi  <br>- **Action Server** → Xử lý logic nâng cao  <br>- **Tracker Store** → Lưu trữ lịch sử hội thoại  <br>- **Lock Store** → Ngăn chặn race condition  <br>- **Filesystem** → Quản lý dữ liệu  <br>- **Agent** → Điều phối chatbot  <br><br>Bạn cần triển khai chatbot với RASA cho dự án cụ thể nào không? 🚀</pre><h3>RASA Core pipeline (Dialog Policies)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*4c19nv1ZJPPEQcaH.png" /></figure><p>Một turn hội thoại sẽ thực hiện như sau :</p><p>Ví dụ:</p><p>Turn 1:</p><p>Người: Ảnh hồ sơ của tôi có vấn đề</p><p>Rasa sẽ phân tích ngữ cảnh từ đầu vào bằng DIET (NLU pipeline)và cho ra:</p><ul><li>intent: người dùng muốn giải quyết thắc mắc về hồ sơ.</li><li>Slot và entities.</li></ul><p>Sau đó sẽ qua dialog management Rasa core pipeline (gồm 3 loại rule, memories, TEDpolices)</p><p>Chi tiết TED polices sử dụng dialog transformers :</p><p>Nó sẽ lấy intent, slot, entities trước đó để chatbot cho ra câu trả lời.</p><p>Quá trình huấn luyện sẽ như sau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*HKnDnIJX0NeGdHPj.png" /></figure><p>Với previous system action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUwCRy0eOotKdsYamHy88A.png" /></figure><p>Và</p><p>Coi như là hành động tiếp theo trong mô hình suy luận. nếu là kiến trúc huấn luyện model nên nó coi như là nhãn thực tế)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*7fqr_mVP6fsT1yarikT3hw.png" /></figure><p>Chatbot: Anh chị đang có vấn đề gì về hồ sơ ạ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*PHw4h18BPUYBWKX-.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b285d8197a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Metrics for QA (Things to note)]]></title>
            <link>https://medium.com/@tuyen66tst/metrics-for-qa-things-to-note-1f9af6871ef4?source=rss-03b80696e5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f9af6871ef4</guid>
            <dc:creator><![CDATA[Tuyentst]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 18:02:09 GMT</pubDate>
            <atom:updated>2024-11-21T18:02:09.771Z</atom:updated>
            <content:encoded><![CDATA[<p>There are two dominant metrics used by many question answering exact <strong>match (EM)</strong> and <strong>F1 score</strong>. These scores are computed on individual question+answer pairs. When multiple correct answers are possible for a given question, the maximum score over all possible correct answers is computed.</p><p>In this blog we will introduction Metrics for QA and Overall EM and F1 scores are computed for a model by averaging over the individual example scores. When you finish reading this blog, you will understand the following concept</p><blockquote>What is Exact Match score ?</blockquote><blockquote>What is F1 score ?</blockquote><blockquote>Coding for Metrics for QA</blockquote><blockquote>Relationship between Exact Match score and F1 score ?</blockquote><h3>What is Exact Match score ?</h3><p>This metric is as simple as it sounds. For each question+answer pair, if the <em>characters</em> of the model’s prediction exactly match the characters of (one of) the True Answer(s), EM = 1, otherwise EM = 0. This is a strict all-or-nothing metric; being off by a single character results in a score of 0. When assessing against a negative example, if the model predicts any text at all, it automatically receives a 0 for that example.</p><pre># Example <br>Question: Where on Earth is free oxygen found?<br>Prediction: water bodies<br>True Answers: [&#39;water&#39;, &quot;in solution in the world&#39;s water bodies&quot;, &quot;the world&#39;s water bodies&quot;]<br>EM: 0 <br>Question: Where on Earth is free oxygen found?<br>Prediction: water<br>True Answers: [&#39;water&#39;, &quot;in solution in the world&#39;s water bodies&quot;, &quot;the world&#39;s water bodies&quot;]<br>EM: 1</pre><h3>What is F1 score ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*VtUKLQFsHa73NIjICFUQ8g.png" /><figcaption>source image: Text bookSpeech and Language Processing by Daniel Jurafsky, James H. Martin</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*3Ab5ntNuo6JCaQqe-v1Odw.png" /><figcaption>General formula F1 score</figcaption></figure><p>With β &gt; 0. F1 score β = 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*S01sWsBb78c3AsXAqih9sw.png" /><figcaption>Formula F1 score</figcaption></figure><p>The measure <strong>precision </strong>and <strong>recall</strong>, evaluating whether the selected words in the predicted answer are actually part of the correct answer.</p><h3>Coding for Metrics for QA</h3><p>Refrences code <a href="https://qa.fastforwardlabs.com/no%20answer/null%20threshold/bert/distilbert/exact%20match/f1/robust%20predictions/2020/06/09/Evaluating_BERT_on_SQuAD.html#Evaluating-a-model-on-the-SQuAD2.0-dev-set-with-HF">this</a></p><pre>!curl -L -O https://raw.githubusercontent.com/huggingface/transformers/master/examples/question-answering/run_squad.py</pre><pre># collapse-hide<br>import json<br>import collections<br>from pprint import pprint<br>import numpy as np<br>import torch<br>from transformers import AutoTokenizer, AutoModelForQuestionAnswering<br>from transformers.data.processors.squad import SquadV2Processor<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;twmkn9/distilbert-base-uncased-squad2&quot;)<br>model = AutoModelForQuestionAnswering.from_pretrained(&quot;twmkn9/distilbert-base-uncased-squad2&quot;)<br>def get_prediction(qid):<br>    # given a question id (qas_id or qid), load the example, get the model outputs and generate an answer<br>    question = examples[qid_to_example_index[qid]].question_text<br>    context = examples[qid_to_example_index[qid]].context_text<br><br>    inputs = tokenizer.encode_plus(question, context, return_tensors=&#39;pt&#39;)<br><br>    outputs = model(**inputs)<br>    answer_start = torch.argmax(outputs[0])  # get the most likely beginning of answer with the argmax of the score<br>    answer_end = torch.argmax(outputs[1]) + 1 <br><br>    answer = tokenizer.convert_tokens_to_string(tokenizer.convert_ids_to_tokens(inputs[&#39;input_ids&#39;][0][answer_start:answer_end]))<br><br>    return answer<br><br># these functions are heavily influenced by the HF squad_metrics.py script<br>def normalize_text(s):<br>    &quot;&quot;&quot;Removing articles and punctuation, and standardizing whitespace are all typical text processing steps.&quot;&quot;&quot;<br>    import string, re<br><br>    def remove_articles(text):<br>        regex = re.compile(r&quot;\b(a|an|the)\b&quot;, re.UNICODE)<br>        return re.sub(regex, &quot; &quot;, text)<br><br>    def white_space_fix(text):<br>        return &quot; &quot;.join(text.split())<br><br>    def remove_punc(text):<br>        exclude = set(string.punctuation)<br>        return &quot;&quot;.join(ch for ch in text if ch not in exclude)<br><br>    def lower(text):<br>        return text.lower()<br><br>    return white_space_fix(remove_articles(remove_punc(lower(s))))<br><br>def compute_exact_match(prediction, truth):<br>    return int(normalize_text(prediction) == normalize_text(truth))<br><br>def compute_f1(prediction, truth):<br>    pred_tokens = normalize_text(prediction).split()<br>    truth_tokens = normalize_text(truth).split()<br>    <br>    # if either the prediction or the truth is no-answer then f1 = 1 if they agree, 0 otherwise<br>    if len(pred_tokens) == 0 or len(truth_tokens) == 0:<br>        return int(pred_tokens == truth_tokens)<br>    <br>    common_tokens = set(pred_tokens) &amp; set(truth_tokens)<br>    <br>    # if there are no common tokens then f1 = 0<br>    if len(common_tokens) == 0:<br>        return 0<br>    <br>    prec = len(common_tokens) / len(pred_tokens)<br>    rec = len(common_tokens) / len(truth_tokens)<br>    <br>    return 2 * (prec * rec) / (prec + rec)<br><br>def get_gold_answers(example):<br>    &quot;&quot;&quot;helper function that retrieves all possible true answers from a squad2.0 example&quot;&quot;&quot;<br>    <br>    gold_answers = [answer[&quot;text&quot;] for answer in example.answers if answer[&quot;text&quot;]]<br><br>    # if gold_answers doesn&#39;t exist it&#39;s because this is a negative example - <br>    # the only correct answer is an empty string<br>    if not gold_answers:<br>        gold_answers = [&quot;&quot;]<br>        <br>    return gold_answers<br><br><br># this processor loads the SQuAD2.0 dev set examples<br>processor = SquadV2Processor()<br>examples = processor.get_dev_examples(&quot;data/squad/&quot;, filename=&quot;dev-v2.0.json&quot;)<br><br><br># generate some maps to help us identify examples of interest<br>qid_to_example_index = {example.qas_id: i for i, example in enumerate(examples)}<br>qid_to_has_answer = {example.qas_id: bool(example.answers) for example in examples}<br>answer_qids = [qas_id for qas_id, has_answer in qid_to_has_answer.items() if has_answer]<br>no_answer_qids = [qas_id for qas_id, has_answer in qid_to_has_answer.items() if not has_answer]<br><br>prediction = get_prediction(answer_qids[1300])<br>example = examples[qid_to_example_index[answer_qids[1300]]]<br><br>gold_answers = get_gold_answers(example)<br><br>em_score = max((compute_exact_match(prediction, answer)) for answer in gold_answers)<br>f1_score = max((compute_f1(prediction, answer)) for answer in gold_answers)<br><br>print(f&quot;Question: {example.question_text}&quot;)<br>print(f&quot;Prediction: {prediction}&quot;)<br>print(f&quot;True Answers: {gold_answers}&quot;)<br>print(f&quot;EM: {em_score} \t F1: {f1_score}&quot;)<br><br>prediction = get_prediction(no_answer_qids[1254])<br>example = examples[qid_to_example_index[no_answer_qids[1254]]]<br><br>gold_answers = get_gold_answers(example)<br><br>em_score = max((compute_exact_match(prediction, answer)) for answer in gold_answers)<br>f1_score = max((compute_f1(prediction, answer)) for answer in gold_answers)<br><br>print(f&quot;Question: {example.question_text}&quot;)<br>print(f&quot;Prediction: {prediction}&quot;)<br>print(f&quot;True Answers: {gold_answers}&quot;)<br>print(f&quot;EM: {em_score} \t F1: {f1_score}&quot;)</pre><h3>Relationship between Exact Match score and F1 score ?</h3><p>First, we need to evaluate the performance of these two metrics on a dev set.</p><pre>Results = {<br>    # a) scores averaged over all examples in the dev set<br>    &#39;exact&#39;: 66.25958056093658,         <br>    &#39;f1&#39;: 69.66994428499025,            <br>    &#39;total&#39;: 11873,  # number of examples in the dev set<br>    <br>    # b) scores averaged over only positive examples (have answers)<br>    &#39;HasAns_exact&#39;: 68.91025641025641,  <br>    &#39;HasAns_f1&#39;: 75.74076391627662,     <br>    &#39;HasAns_total&#39;: 5928, # number of positive examples<br>    <br>    # c) scores averaged over only negative examples (no answers)<br>    &#39;NoAns_exact&#39;: 63.61648444070648, <br>    &#39;NoAns_f1&#39;: 63.61648444070648, <br>    &#39;NoAns_total&#39;: 5945, # number of negative examples<br>    <br>    # d) given probabilities of no-answer for each example, what would the best scores and thresholds be?<br>    &#39;best_exact&#39;: 66.25958056093658, <br>    &#39;best_exact_thresh&#39;: 0.0, <br>    &#39;best_f1&#39;: 69.66994428499046, <br>    &#39;best_f1_thresh&#39;: 0.0<br>}</pre><p>The first three blocks of the Results output are pretty straightforward. EM and F1 scores are reported over a) the full dev set, b) the set of positive examples, and c) the set of negative examples. This can provide some insight into whether a model is performing adequately on both answer and no-answer questions. (This particular model is pretty bad at no-answer questions).</p><p>From the results, we can see that the F1 score is usually higher than the Exact Match (EM) score. This is because EM and F1 scores are typically calculated on different levels. EM is calculated at the character level, meaning the entire predicted answer must match the reference answer exactly. On the other hand, F1 is calculated on the word level, where partial matches count, meaning it takes into account precision and recall for each word in the prediction.</p><p>As a result, it is common for the F1 score to be higher than the EM score. However, if the F1 score is lower than the EM score, it could indicate a potential issue with your model or the evaluation code.</p><p><strong>Ways to Check and Resolve the Issue:</strong></p><p><strong>1. Check with a dataset containing actual answers:</strong></p><ul><li>Use the same dataset for both training and evaluation.</li><li>Verify whether the issue with the EM score is due to the dataset containing many empty answers.</li></ul><p><strong>2. Check with a separate dataset:</strong></p><ul><li>Split the dataset into distinct training and evaluation sets, including questions with many empty answers.</li><li>Confirm this to rule out the possibility that the issue stems from the data itself.</li></ul><p><strong>3. Analyze EM and F1 scores for both cases:</strong></p><ul><li>Compare the results to eliminate assumptions and understand whether the issue is related to specific data characteristics or model behavior.</li></ul><h3>Conclusion</h3><p>Evaluation in Question Answering (QA) is crucial, and there are various metrics to assess predicted and correct answers. In this blog, we introduce two commonly used metrics and explain their relationship, which can help you improve your model or code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f9af6871ef4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimum Bayes Risk Decoding]]></title>
            <link>https://medium.com/@tuyen66tst/minimum-bayes-risk-decoding-for-machine-translate-3166ebeb27c4?source=rss-03b80696e5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3166ebeb27c4</guid>
            <dc:creator><![CDATA[Tuyentst]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 17:59:42 GMT</pubDate>
            <atom:updated>2024-11-09T05:07:38.107Z</atom:updated>
            <content:encoded><![CDATA[<p>Minimum Bayes risk or MBR decoding is an alternative decoding algorithm that can work even better than <a href="https://www.bing.com/search?q=beam+search&amp;cvid=2a87a3d4421043beb9fa5cd432eed84c&amp;gs_lcrp=EgRlZGdlKgYIABBFGDsyBggAEEUYOzIGCAEQRRg7MgYIAhBFGDsyBggDEEUYOzIGCAQQABhAMgYIBRAAGEAyBggGEEUYPDIGCAcQRRg8MgYICBBFGDzSAQgyMTAwajBqOagCCLACAQ&amp;FORM=ANAB01&amp;PC=U531">beam search</a> and also tends to be better than the other decoding algorithms like temperature sampling.</p><p>In this blog, we will introduce Minimum Bayes Risk Decoding and how it is used in tasks NLP; a special task is in translation machine. When you finish reading this blog, you will understand the following concept:</p><blockquote><strong>What is Minimum Bayes risk or MBR decoding ?</strong></blockquote><blockquote><strong>How does MBR decoding work?</strong></blockquote><blockquote><strong>Benefits for MBR decoding</strong></blockquote><blockquote><strong>Drawbacks for MBR decoding</strong></blockquote><h3>What is Minimum Bayes risk or MBR decoding ?</h3><p>Minimum Bayes Risk (MBR) decoding is a method for choosing the outputs of a machine learning system based not on the output with the highest probability, but the output with the lowest risk (expected error) among multiple candidates.</p><p>The common method used is that the decoding method selects the output with the greatest probability. Take, for example, a popular decoding method, beam search decoding.</p><p><strong>Introduce to Beam Search Decoding</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*jAaokdD3Z52hs_FEoY1vIw.jpeg" /><figcaption>Source: Chapter 13.4 Decoding in MT: Beam Search in Speech and Language Processing by Daniel Jurafsky[1]</figcaption></figure><p>The image above illustrates how beam search decoding works with a beam width of k = 2. At each time step, we choose the k best hypotheses, form the V possible extensions of each, score those k x V hypotheses and choose the best k = 2 to continue. At time 1, the frontier has the best 2 options from the initial decoder state: arrived and the. We extend each, compute the probability of all the hypotheses so far (arrived the, arrived aardvark, the green, the witch) and again chose the best 2 (the green and the witch) to be the search frontier. The images on the arcs schematically represent the decoders that must be run at each step to score the next words (for simplicity not depicting cross-attention).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wh7mjliYdI1KOhup8i9naw.jpeg" /><figcaption>Source: Chapter 13.4 Decoding in MT: Beam Search in Speech and Language Processing by Daniel Jurafsky[1]</figcaption></figure><p>In the next step, each of the <strong><em>k </em></strong>hypotheses undergoes gradual expansion until an EOS is generated indicating that a complete candidate output has been found.. During each decoding phase, a softmax is generated over the entire vocabulary to extend each hypothesis, exploring every potential next word. Given V as the full vocabulary size, this process produces <strong><em>k x V</em></strong> hypotheses. However, only the top k hypotheses with the highest probability <em>P(y_i | x, y_{&lt;i}) </em>are retained. Here, P(y_i | x, y_{&lt;i}) represents the product of the current word’s probability and the cumulative probability of the word sequence leading to it (See more detail above image)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*3ztaXPiLYFe3YfjTwmM5dg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*Z62363ykYaAuvlY0GKQoVg.jpeg" /></figure><p>This function score(y) is final scoring function, where a higher score indicates a higher likelihood that the sentence is accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*ixn0aT6f5YVft_k2HGtI7A.png" /></figure><p>In practice, the function score(y) needs an additional hyperparameter aaa (usually is 0.75) to penalize long sentences. Beauce long sentences tend to score lower than shorter ones.</p><blockquote>(1) From part introduce to beam search decoding, Following <a href="https://www.assemblyai.com/blog/decoding-strategies-how-llms-choose-the-next-word/">Decoding Strategies: How LLMs Choose The Next Word</a> conclusion that “However, Beam Search often underperforms in open-ended text generation tasks. <strong>These studies </strong><a href="https://arxiv.org/pdf/1904.09751?ref=assemblyai.com"><strong>reveal</strong></a><strong> that Beam Search tends to produce repetitive and unnatural text, showing clear patterns of degeneration</strong>. In fact, Beam Search text tends to converge on a subset of the model’s vocabulary. “</blockquote><p>Thus, Minimum Bayes risk or MBR decoding is an alternative decoding algorithm that can work even better than <a href="https://en.wikipedia.org/wiki/Beam_search">beam search</a> (1) and also tends to be better than the other decoding algorithms like temperature sampling.</p><h3><strong>How does MBR decoding work?</strong></h3><p>In practice, we don’t know the perfect set of translations for a given sentence. So the standard simplification used in MBR decoding algorithms is to instead choose the candidate translation which is most similar (by some measure of goodness-of f it) with some set of candidate translations. We’re essentially approximating the enormous space of all possible translations U with a smaller set of possible candidate translations Y.</p><p>Given this set of possible candidate translations Y, and some similarity or align ment function util, we choose the best translation ŷ as the translation which is most similar to all the other candidate translations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*7XOKXVeZZasxk9AdxZ7AWw.jpeg" /></figure><p>Various util functions can be used, like chrF or BERTscore or BLEU. We can get the set of candidate translations by sampling using one of the basic sampling algorithms like temperature sampling; good results can be obtained with as few as 32 or 64 candidates.</p><p>Benefits for MBR decoding</p><p>In Neural Machine Translation operate good and solve alternative for methods common as Beam search decoding, also tends to be better than the other decoding algorithms like temperature sampling.</p><p>The flexibility of the expected risk equation allows us to pile on different loss functions on to the decoding stage</p><h3><strong>Drawbacks for MBR decoding</strong></h3><p>Requires more computational resources due to the need to calculate an additional utility function.</p><p>Depends on the set of possible candidate translations Y ; if the set is small, it will encounter many limitations.</p><p>References</p><p>[1] Chapter 13.4 Decoding in MT: Beam Search in Speech and Language Processing by Daniel Jurafsky</p><p>[2] Blog Decoding Strategies: How LLMs Choose The Next Word by ASSEMBLYAI</p><p>[3] Mathias Müller and Rico Sennrich. 2021. Understanding the properties of minimum bayes risk decoding in neural machine translation. ACL.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3166ebeb27c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>