<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://esoba.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://esoba.github.io/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-10-16T10:31:48-07:00</updated><id>https://esoba.github.io/feed.xml</id><title type="html">Elijah Soba</title><subtitle>A logbook of notes, experiments, and lessons from working in machine learning.</subtitle><entry><title type="html">I don’t use SQL as much as I should</title><link href="https://esoba.github.io/blog/2024/i-dont-use-sql-but-i-should/" rel="alternate" type="text/html" title="I don’t use SQL as much as I should" /><published>2024-02-26T09:00:10-08:00</published><updated>2024-02-26T09:00:10-08:00</updated><id>https://esoba.github.io/blog/2024/i-dont-use-sql-but-i-should</id><content type="html" xml:base="https://esoba.github.io/blog/2024/i-dont-use-sql-but-i-should/"><![CDATA[<h2 id="intro">Intro</h2>

<p>The title kind of speaks for itself, but I admittedly haven’t had many opportunities to work with SQL. Because I am in the ML field and also because my technical title for work is Data Scientist, it is assumed that I know SQL and use it on a day to day basis. The truth is, I am often looking at open source datasets or getting data handed to me (a bit privileged, I know). I say I know SQL, but really I only know the basics and don’t get to practice these skills very often. Luckily, I had some exposure to it in college and know Pandas pretty well so I can dig through some documentation and understand whats going on.</p>

<p>The guide below is for people who are in my shoes - ML practicioners who should know SQL just by virtue of just being in the field. Almost every Data Science, Data Engineer, Machine Learning Engineer job posting I’ve seen has some sort of requirement on SQL, so even if you never use SQL it will be good to know.</p>

<p>I got a lot of this material from random sources and YouTube videos (all will be linked below), but I think the best resource for my learning was <a href="https://selectstarsql.com/">select star sql</a>. I have no affiliation with the person who made this site, but going through his chapters was super intuitive and interactive. His book gives you the ability to run queries in real time (I’ll just be showing code snippets here) which really solidified my learning.</p>

<p>Also because I need some examples to actually show SQL in action, I opted to test out the knowledge on a select number of hackerrank SQL questions. I am not a fan of companies using hackerrank to weed out applicants (which I talk about in a <a href="https://selectstarsql.com/">blog post</a>), but for the sake of building skills I think it is pretty useful (especially here). There will be some basic examples in the sections describing core concepts, and harder examples towards the end</p>

<h2 id="different-types-of-sql">Different types of SQL</h2>

<p>Whenver I see SQL in the wild, its always followed by some modifier: PostgreSQL, MySQL, SQLite (what I first learned in college), etc. I never really understood the difference, but its about time I (we) do.</p>

<p>The way I have come to understand the differences is that SQL is a standardized language used to manage/manipulate relational databases. All of the other flavors (like the ones that I listed above) is a specific relational database management system (RDBMS) that uses SQL as its querying language. The different flavors can also provide additional features/functionalities specific to the database system.</p>

<p>As one <a href="https://www.reddit.com/r/SQL/comments/e0ao31/newbie_what_the_difference_between_sql_and_mysql/">redditor</a> put it, SQL = the English language, MySQL (or any other flavor) = a novel that was written using the English language. In terms of the additional functionalities mentioned above, you can think of a huge chunk (lets call it 95%) of the base functionality being the same and 5% being flavor specific.</p>

<p>For the guide, I am going to go through SQLite because it is the <a href="https://www.sqlite.org/mostdeployed.html">most widely deployed</a> and the one I am most familiar with. Assuming the information I just mentioned above is true, the knowledge below should be widely applicable to all flavors.</p>

<h2 id="convention">Convention</h2>
<p>If you see SQL in the wild, its typically written out in a pretty consistent (and human readable) format. The main conventions in SQL are the following:</p>
<ul>
  <li>SQL specific keywords are capitalized, while database schema specific keywords (like table names) are lowercase.
    <ul>
      <li>Some flavors of SQL can be case sensitive, verify that the flavor doesn’t have a restriction on this</li>
    </ul>
  </li>
  <li>As long as you don’t smush two words together, SQL is not very sensitive to whitespace. Improve readability by putting each command on a new line</li>
  <li>Arithmetic stays in integer form unless .0 is added to the hardcoded numbers. A common trick is to multiply a number by 1.0 to make it decimal</li>
  <li>Strings are denoted by single quotes</li>
  <li>Semicolons at the end of queries separate individual queries from each other</li>
</ul>

<h2 id="basic-commands">Basic commands</h2>

<p>SELECT:</p>
<ul>
  <li>Indicates what you want to output</li>
  <li>The * wildcard means “all columns”</li>
  <li>You can make your own columns from some combination of other columns</li>
  <li>You can use the AS keyword to alias some column</li>
</ul>

<p>In pandas, this is analogous to df[‘column_name’] or just simple look up. If you wanted to combine different columns, you could index columns and do whatever operation you want. For example df[‘col1’] + df[‘col2’]. The aliasing comes from whatever you decide to name the resultant dataframe</p>

<p>FROM:</p>
<ul>
  <li>Indicates what table in the database should be used</li>
  <li>Technically don’t need the FROM block if nothing from the table is being used</li>
</ul>

<p>With pandas it is assumed that the dataframe you have is not connected to multiple potential dataframes so the FROM keyword does not have a good analog.</p>

<p>WHERE:</p>
<ul>
  <li>Indicates what filters should be applied before outputting</li>
  <li>Done with boolean indexing using operators like &gt;, = (not ==), etc.</li>
  <li>For strings, SQL supports a couple different, more powerful operators
    <ul>
      <li>Use the LIKE to do wildcard searches</li>
      <li>LIKE ‘%val’ means any combo of strings + val</li>
      <li>LIKE ‘_val’ means single character match + val</li>
      <li>See documenation for more like this</li>
    </ul>
  </li>
  <li>To determine is something is NULL, use the keyword IS (val IS null)</li>
</ul>

<p>This is equivalent to something like df[df[‘col1’] &lt; 5] except of course you can replace &lt; with any operator and 5 with any desired filter value. Like in pandas, it is up to you to make sure the operator + filter value you choose is in line with the datatype you are dealing with (for example if col1 was all string data, the expression above wouldnt make sense).</p>

<p>NOTE: The mental model I like to keep for WHERE (or pandas boolean indexing) is for loops. I imagine every WHERE clause or df[df[‘col1’] &lt; 5] as being:</p>
<ul>
  <li>for row in df (or table) if row meets clause output row else skip</li>
</ul>

<p><a href="https://www.hackerrank.com/challenges/japanese-cities-attributes/problem">EXAMPLE</a></p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="o">*</span> 
<span class="k">FROM</span> <span class="n">CITY</span> 
<span class="k">WHERE</span> <span class="n">countrycode</span> <span class="o">=</span> <span class="s1">'JPN'</span>
</code></pre></div></div>

<p>ORDER BY:</p>
<ul>
  <li>Indicates the ordering of output based on a colum</li>
  <li>You can order by multiple things by separating columns by commas</li>
</ul>

<p>In pandas, this is like calling the sort_values() method</p>

<p>LIMIT:</p>
<ul>
  <li>Indicates how many results should be output</li>
</ul>

<p>This is equivalent to making your query in pandas and adding [:limit number] or [limit number:]. Essentially indexing the final output.</p>

<h2 id="aggregating">Aggregating</h2>

<p>NOTE: The flavor of SQL you use may have different syntax than the aggregators here or additional aggregate functionality. Refer to the documentation for your specific flavor for details. For completion, below are some of the most common ones</p>

<p>COUNT:</p>
<ul>
  <li>Counts the number of non-null rows in a column</li>
  <li>Can use COUNT(*) to get the length of an entire table
    <ul>
      <li>Counts rows as long as any one of their columns is non-null</li>
    </ul>
  </li>
</ul>

<p>DISTINCT:</p>
<ul>
  <li>Returns only unique parts of a column and no duplicates</li>
</ul>

<p>SUM/MIN/MAX/AVG:</p>
<ul>
  <li>Does the aggregation specified</li>
</ul>

<p>LENGTH/LEN:</p>
<ul>
  <li>Returns the number of characters in a string</li>
</ul>

<p><a href="https://www.hackerrank.com/challenges/weather-observation-station-18/">EXAMPLE</a></p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">ROUND</span><span class="p">(</span><span class="k">MAX</span><span class="p">(</span><span class="n">lat_n</span><span class="p">)</span> <span class="o">-</span> <span class="k">MIN</span><span class="p">(</span><span class="n">lat_n</span><span class="p">)</span> <span class="o">+</span> <span class="k">MAX</span><span class="p">(</span><span class="n">long_w</span><span class="p">)</span> <span class="o">-</span> <span class="k">MIN</span><span class="p">(</span><span class="n">long_w</span><span class="p">),</span> <span class="mi">4</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">STATION</span>
</code></pre></div></div>

<p>NOTE: In most cases, if you try to output a column and an aggregation from SELECT you will get just one output. The column output will be some singular random output instead. This is because SQL doesn’t know how to output a singular value (which the aggregator returns) with multiple values from the specified column</p>

<p>You can do aggregating either on the entire table, or a subset of the table (more info in the nested query section)</p>

<h2 id="group-by">Group By</h2>
<p>GROUP BY:</p>
<ul>
  <li>Gathers identical column values to allow aggregators to be used on them</li>
  <li>Always comes after a WHERE block</li>
</ul>

<p>This is pretty much identical to pandas groupby.</p>

<p>HAVING:</p>
<ul>
  <li>Allows you to filter after output after performing group by logic</li>
  <li>Essentially the WHERE clause, except specifically for groupby outputs
    <ul>
      <li>WHERE happens before grouping and aggregation</li>
    </ul>
  </li>
</ul>

<p><a href="https://www.hackerrank.com/challenges/earnings-of-employees/problem">Example</a></p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">salary</span><span class="o">*</span><span class="n">months</span> <span class="k">as</span> <span class="n">tot_sal</span><span class="p">,</span> <span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">employee</span>
<span class="k">GROUP</span> <span class="k">BY</span> <span class="n">tot_sal</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">tot_sal</span> <span class="k">DESC</span>
<span class="k">LIMIT</span> <span class="mi">1</span>
</code></pre></div></div>

<p>NOTES: 
GROUP BY breaks the NOTE above because if you SELECT a column and some aggregate when a groupby is introduced, the aggregate will be performed first allowing each column to have some number associated with it. This is of course assuming that you are consistent with what you are grouping by (For example, SELECT <strong>city</strong>, COUNT(city) FROM city_table GROUP BY <strong>city</strong>)</p>

<p>If you group by multiple objects and there is nothing to display for a particular group, nothing will be returned. I think the best explanation for this can be found in the (decade age example)[https://selectstarsql.com/longtail.html]. Essentially if (group1, group2) has an aggregation that doesnt exist, it will not show up in the output.</p>

<p>In pandas, you get some group by functionality out of the box. For example, the value_counts() method is really just a short hand for groupby(‘column’).size() (or .count() if you do not want to consider NaN values). I am not sure if you get the same OOB funcionality with SQL</p>

<h2 id="nested-queriessubsets">Nested Queries/Subsets</h2>

<p>CASE WHEN:</p>
<ul>
  <li>A way to introduce if-else logic into SQL</li>
  <li>The syntax is CASE WHEN clause THEN result …(more statements here)… ElSE result END (END needed to conclude statement)</li>
</ul>

<p>You can use this to create subsets of the table in a specified way (you get to specify each case or if statement)</p>

<p><a href="https://www.hackerrank.com/challenges/binary-search-tree-1/problem?isFullScreen=true">EXAMPLE</a>:</p>

<p>Without CASE WHEN</p>
<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">N</span><span class="p">,</span> <span class="s1">'Leaf'</span>
<span class="k">FROM</span> <span class="n">BST</span>
<span class="k">WHERE</span> <span class="n">N</span> <span class="k">NOT</span> <span class="k">IN</span> <span class="p">(</span><span class="k">SELECT</span> <span class="k">DISTINCT</span> <span class="n">P</span> <span class="k">FROM</span> <span class="n">BST</span> <span class="k">WHERE</span> <span class="n">P</span> <span class="k">IS</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">)</span>

<span class="k">UNION</span>

<span class="k">SELECT</span> <span class="n">N</span><span class="p">,</span> <span class="s1">'Inner'</span>
<span class="k">FROM</span> <span class="n">BST</span>
<span class="k">WHERE</span> <span class="n">N</span> <span class="k">IN</span> <span class="p">(</span><span class="k">SELECT</span> <span class="n">P</span> <span class="k">FROM</span> <span class="n">BST</span> <span class="k">WHERE</span> <span class="n">P</span> <span class="k">IS</span> <span class="k">NOT</span> <span class="k">NULL</span> <span class="k">AND</span> <span class="n">P</span> <span class="o">!=</span> <span class="p">(</span><span class="k">SELECT</span> <span class="n">N</span> <span class="k">FROM</span> <span class="n">BST</span> <span class="k">WHERE</span> <span class="n">P</span> <span class="k">is</span> <span class="k">null</span><span class="p">))</span>

<span class="k">UNION</span>

<span class="k">SELECT</span> <span class="n">N</span><span class="p">,</span> <span class="s1">'Root'</span>
<span class="k">FROM</span> <span class="n">BST</span>
<span class="k">WHERE</span> <span class="n">P</span> <span class="k">is</span> <span class="k">null</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">N</span><span class="p">;</span>
</code></pre></div></div>

<p>WITH CASE WHEN</p>
<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">N</span><span class="p">,</span> 
<span class="k">CASE</span> 
    <span class="k">WHEN</span> <span class="n">P</span> <span class="k">IS</span> <span class="k">null</span> <span class="k">THEN</span> <span class="s1">'Root'</span>
    <span class="k">WHEN</span> <span class="n">N</span> <span class="k">NOT</span> <span class="k">IN</span> <span class="p">(</span><span class="k">SELECT</span> <span class="n">P</span> <span class="k">FROM</span> <span class="n">BST</span> <span class="k">WHERE</span> <span class="n">P</span> <span class="k">is</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">)</span> <span class="k">THEN</span> <span class="s1">'Leaf'</span>
    <span class="k">ELSE</span> <span class="s1">'Inner'</span>
<span class="k">END</span>
    
<span class="k">FROM</span> <span class="n">BST</span> 
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">N</span><span class="p">;</span>
</code></pre></div></div>

<p>Sometimes, you need to aggregate both within groups and across the entire dataset. Unfortunately, this cannot be done at the same time with a single query. To bypass this, you can create a query that generates a subset of the data, and wrap it in parenthesees to isolate it from the rest of the query.</p>

<h2 id="joins">Joins</h2>

<p>LEFT/RIGHT/OUTER/INNER JOIN:</p>
<ul>
  <li>Joins two tables together based on the specified <a href="https://www.w3schools.com/sql/sql_join.asp">JOIN type</a></li>
  <li>By default, using the JOIN keyword will do an INNER JOIN</li>
  <li>You typically join on a key that is the same across different tables
    <ul>
      <li>FROM table1 JOIN table 2 on table1.uid = table2.uid</li>
    </ul>
  </li>
  <li>You can join a table with itself (Useful when you make subsets w/different columns)</li>
  <li>You can alias without using AS</li>
  <li>You can optionally join on another boolean operator (useful if you don’t care about duplicates)</li>
</ul>

<p><a href="https://www.hackerrank.com/challenges/asian-population/problem?isFullScreen=true">EXAMPLE</a>:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="k">SUM</span><span class="p">(</span><span class="k">c</span><span class="p">.</span><span class="n">population</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">city</span> <span class="k">c</span>
<span class="k">JOIN</span> <span class="n">country</span> <span class="n">co</span> <span class="k">ON</span> <span class="k">c</span><span class="p">.</span><span class="n">countrycode</span> <span class="o">=</span> <span class="n">co</span><span class="p">.</span><span class="n">code</span>
<span class="k">WHERE</span> <span class="n">co</span><span class="p">.</span><span class="n">continent</span> <span class="o">=</span> <span class="s1">'Asia'</span>
</code></pre></div></div>
<p>NOTE: As mentioned above, we aliased city and country without specifying AS</p>

<h2 id="other-important-keywords">Other important keywords</h2>
<p>RIGHT/LEFT:</p>
<ul>
  <li>Extract characters from a string starting from either left or right - LEFT/RIGHT(“my_str”, # char to extract)</li>
</ul>

<p><a href="https://www.hackerrank.com/challenges/weather-observation-station-6/problem?isFullScreen=true">Example</a>:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="k">DISTINCT</span> <span class="n">city</span>
<span class="k">FROM</span> <span class="n">station</span>
<span class="k">WHERE</span> <span class="k">LEFT</span><span class="p">(</span><span class="n">city</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="k">in</span> <span class="p">(</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'e'</span><span class="p">,</span> <span class="s1">'i'</span><span class="p">,</span> <span class="s1">'o'</span><span class="p">,</span> <span class="s1">'u'</span><span class="p">)</span>
</code></pre></div></div>

<p>SUBSTR:</p>
<ul>
  <li>Extract a substring from a string -  SUBSTR(“my_str”, start_position, # of extract characters)</li>
  <li>Can modify the above example to use substr instead of left</li>
</ul>

<p>CONCAT:</p>
<ul>
  <li>Concatentate strings together - CONCAT (string1, string2, …)</li>
</ul>

<p><a href="https://www.hackerrank.com/challenges/the-pads/problem?isFullScreen=true">Example</a>:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">CONCAT</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="s1">'('</span><span class="p">,</span> <span class="k">LEFT</span><span class="p">(</span><span class="n">occupation</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="s1">')'</span><span class="p">)</span> <span class="k">as</span> <span class="n">paren</span>
<span class="k">FROM</span> <span class="n">occupations</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">name</span><span class="p">;</span>

<span class="k">SELECT</span> <span class="n">CONCAT</span><span class="p">(</span><span class="s1">'There are a total of '</span><span class="p">,</span> <span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">),</span> <span class="s1">' '</span><span class="p">,</span> <span class="k">LOWER</span><span class="p">(</span><span class="n">occupation</span><span class="p">),</span> <span class="s1">'s.'</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">occupations</span>
<span class="k">GROUP</span> <span class="k">BY</span> <span class="n">occupation</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span>
</code></pre></div></div>

<p>WITH:</p>
<ul>
  <li>Define a subset of a table to reference later - WITH reference_name AS (Subtable query)</li>
</ul>

<p>UNION:</p>
<ul>
  <li>Combine the result set of two or more SELECT statements</li>
</ul>

<p>BETWEEN:</p>
<ul>
  <li>Operator that selects values within a given range - col BETWEEN val1 AND val2</li>
</ul>

<p><a href="https://www.hackerrank.com/challenges/the-report/problem?isFullScreen=true">EXAMPLE</a></p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">WITH</span> <span class="n">comb</span> <span class="k">AS</span> 
<span class="p">(</span><span class="k">SELECT</span> <span class="n">s</span><span class="p">.</span><span class="n">name</span><span class="p">,</span> <span class="k">g</span><span class="p">.</span><span class="n">grade</span><span class="p">,</span> <span class="n">s</span><span class="p">.</span><span class="n">marks</span>
<span class="k">FROM</span> <span class="n">students</span> <span class="n">s</span>
<span class="k">LEFT</span> <span class="k">JOIN</span> <span class="n">grades</span> <span class="k">g</span> 
<span class="k">ON</span> <span class="n">s</span><span class="p">.</span><span class="n">marks</span> <span class="k">BETWEEN</span> <span class="k">g</span><span class="p">.</span><span class="n">min_mark</span> <span class="k">AND</span> <span class="k">g</span><span class="p">.</span><span class="n">max_mark</span><span class="p">)</span>

<span class="p">(</span><span class="k">SELECT</span> <span class="n">name</span><span class="p">,</span> <span class="n">grade</span><span class="p">,</span> <span class="n">marks</span>
<span class="k">FROM</span> <span class="n">comb</span>
<span class="k">WHERE</span> <span class="n">grade</span> <span class="o">&gt;=</span> <span class="mi">8</span><span class="p">)</span>

<span class="k">UNION</span> 

<span class="p">(</span><span class="k">SELECT</span> <span class="k">NULL</span> <span class="k">as</span> <span class="n">name</span><span class="p">,</span> <span class="n">grade</span><span class="p">,</span> <span class="n">marks</span>
<span class="k">FROM</span> <span class="n">comb</span>
<span class="k">WHERE</span> <span class="n">grade</span> <span class="o">&lt;</span> <span class="mi">8</span><span class="p">)</span>

<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">grade</span> <span class="k">DESC</span><span class="p">,</span> <span class="n">name</span> <span class="k">ASC</span><span class="p">;</span>
</code></pre></div></div>

<h2 id="more-examples">More Examples</h2>
<p>Coming soon!</p>

<h2 id="note-on-llms-for-sql">Note on LLMs for SQL</h2>

<p>Because the base functionality of SQL is very close to written language, it is is the perfect candidate for a task that can be done with Large Language Models (LLMs). For the examples above in hackerrank, GPT-4 was able to reproduce most of the answers I wrote by just providing a description of the task and database schema. The ones that it did get wrong could easily be fixed by understanding all of the concepts above. There are also some LLMs out there that were fine-tuned</p>

<h2 id="sources">Sources</h2>
<p><a href="https://selectstarsql.com/">select star sql</a>
<a href="https://www.youtube.com/watch?v=gm6tNK_iOHs&amp;list=PLR0triVyTrBWOLNu3ato7Y9hnGVyhTe1c">basic sql YT playlist</a>
<a href="https://www.youtube.com/watch?v=zsjvFFKOm3c&amp;pp=ygUMc3FsIGZpcmVzaGlw">SQL in 100 seconds</a>
<a href="https://www.youtube.com/watch?v=vpzO8QTrgbc&amp;pp=ygUOc3FsIGhhY2tlcnJhbms%3D">guy answers all hackerrank sql questions</a></p>]]></content><author><name></name></author><category term="basic" /><category term="cs-skills" /><summary type="html"><![CDATA[Intro SQL guide for people who should know SQL]]></summary></entry><entry><title type="html">LLMs in layman’s term</title><link href="https://esoba.github.io/blog/2024/llms-in-layman-terms/" rel="alternate" type="text/html" title="LLMs in layman’s term" /><published>2024-02-26T09:00:10-08:00</published><updated>2024-02-26T09:00:10-08:00</updated><id>https://esoba.github.io/blog/2024/llms-in-layman-terms</id><content type="html" xml:base="https://esoba.github.io/blog/2024/llms-in-layman-terms/"><![CDATA[<h2 id="llm-talk-in-the-wild">LLM talk in the wild</h2>

<p>The other day, I heard one of my friends (who works in some business capacity) talking about the work his team was supporting. He said something along the lines of:</p>

<p>“I’m working with this AI team that has a model thats able to make classifications on text. Its the same type of technology that ChatGPT uses.”</p>

<p>This was before I knew he was on the business side of things, so I excitedly asked him “Are you working with transformers?!?” to which he replied “uuhhhhh maybe”.</p>

<p>In another interaction, one of my friends asked me about the work I was doing. He is an actuary and I know he understands/loves math so I started divulging into some of the specifics about LLMs and the work I was doing in Generative AI. At some point he interrupted me with two statements:</p>

<p>“Doesn’t ChatGPT just look up information on the internet before answering someones question?”</p>

<p>“Wait so how does the model use the internet”</p>

<p>A final interaction that stuck with me was talking to my friends cousin about a business opportunity in medical AI. He was a genius doctor/business man that wanted to know how he could integrate “AI” into his workflows to make the doctors office more efficient. I was super excited and started brainstorming a whole bunch of Generative AI ideas like QA over medical documents, automatic scribing, etc. I put together a little pitch and at the end he mentioned it wasn’t exactly what he was looking for. He countered with:</p>

<p>“Imagine if we took the app for our practice and sent automated messages reminding people to eat right or get more steps in for the day”.</p>

<p>As the hype for Generative AI grows (as it should!), terms like ChatGPT, LLMs, AI, Machine Learning, etc. are all getting bundled together to mean the same thing. I think if you are someone who wants to use Generative AI, it is worth it to understand at a high level what LLMs can/cannot do and how they work. This will not only ground expectations for Generative AI applications, but also make it easier to talk to talent who will eventually make those applications.</p>

<h2 id="llms-described-for-a-non-technical-audience">LLMs described for a non-technical audience</h2>

<p>Imagine you gave a person, let’s call her Gill, a huge encyclopedia and asked her to read it. After reading, you give her a test: a bunch of open ended questions about the content of the book.</p>

<p>How well do you think she would perform?</p>

<p>Whatever metric you have in your mind, how much better would she do if she could read the encyclopedia multiple times?</p>

<p>Assuming she was able to pass the test eventually, what would the performance look like if she was given a similar test but with information not contained in the encyclopedia?</p>

<p>If you can understand this mental model, you can understand LLMs! To get to LLMs, do the following:</p>
<ul>
  <li>Replace the person with a statistical model designed to understand the relationship between texts</li>
  <li>Replace the encyclopedia with the entire internet</li>
  <li>Replace the test with any user question</li>
</ul>

<p>Any question you have about LLMs, first ask the question to Gill. For example:</p>

<p>(LLM Question)
Why do LLMs return non-factual information?</p>

<p>LLM Related Answer:</p>
<ul>
  <li>LLMs learn a probability distribution over next possible tokens in a sequence. When you give an LLM an input it will try to complete it by sampling tokens it thinks should come next (according to the distribution it learned). They are auto-regressive, so they use their own outputs to generate more input. LLMs technically don’t memorize information, if it did it would overfit to the exact specific information it was trained on. Because everything is based on probabilities, sampling can cause information to be false. Likewise, because it is autoregressive, one improperly sampled token creates a downstream affect that can lead to a non-factual answer. Just because a LLM may have seen a particular bit of information during training, doesn’t mean the signal was strong enough to influence the learned probability distribution.</li>
</ul>

<p>(Converted Gill Question)
Why did you get that question on the test wrong?</p>

<p>Gills Answer:</p>

<p>I read about information regarding the question, but I couldnt remember during the test. It was such a small part of the encyclopedia so I couldnt recall the exact details.</p>

<p>(LLM Question)
Can LLMs do math?</p>

<p>Technically, numbers are also encoded as tokens so they can generate output with numbers. Asking something like “What is 2 + 2” could lead to an LLM, by virtue of its training, to output a high probability for the token “4”. In this sense it can do math, but realistically it is just text completion in a math setting. If you start asking more complex questions, performance will drop considerably because LLMs are text reasoning engines not math reasoning engines. To get LLMs to do math, a better way is to ask the LLM what would be needed to solve the problem (like a particular technique) and have it send extracted numbers to a downstream computer program that can accept the inputs. For example if you ask it what is 100 + 300/2, you can have it reason what steps it needs to take and hook it up to a calculator to do the actual computations.</p>

<p>(Converted Gill Question)
Based on what you read in the math section of the encylopedia, can you solve this math problem for me?</p>

<p>I read about how to solve something like this, but I’ve never had to actual do it. I understand what is being asked but I can’t solve it.</p>

<p>I could go on, but most of these questions are going to be future blog posts! Next time you have a high level question about LLMs, think of Gill first.</p>]]></content><author><name></name></author><category term="non-technical" /><category term="NLP" /><category term="GenAI" /><summary type="html"><![CDATA[Explaining LLMs with analogies]]></summary></entry><entry><title type="html">How do pre-trained sentence embeddings work?</title><link href="https://esoba.github.io/blog/2024/how-do-pre-trained-embeddings-work/" rel="alternate" type="text/html" title="How do pre-trained sentence embeddings work?" /><published>2024-02-26T09:00:10-08:00</published><updated>2024-02-26T09:00:10-08:00</updated><id>https://esoba.github.io/blog/2024/how-do-pre-trained-embeddings-work</id><content type="html" xml:base="https://esoba.github.io/blog/2024/how-do-pre-trained-embeddings-work/"><![CDATA[<h2 id="intro">Intro</h2>

<p>When I first got into NLP, my first couple projects involved building some basic classification, clustering, and RAG algorithms using <a href="https://www.sbert.net/">sentence embeddings</a> or <a href="https://platform.openai.com/docs/guides/embeddings">OpenAI embeddings</a>. I think this was a great start because it made me realize that <a href="">NLP isn’t much different than other ML areas</a>, but as I kept going down the NLP rabbit hole I realized I didn’t truly understand these embeddings.</p>

<p>Looking back, I don’t blame myself too much for my lack of understanding because word embeddings are a lot more intuitive. Without diving into specifics (which can be found <a href="">here</a>), word embeddings are created by analyzing the relationships between words and surrounding context in a corpus. The output of a perfect word embedding model are vectors whose geometric similarity (like cosine similarity) are representative of their semantic similarity. Thus, we can expect words with similar meanings to be closer together in the vector space.</p>

<p>Even though I understood how word embeddings worked, I struggled with sentences for a couple different reasons. These were some of my qualms:</p>
<ul>
  <li>Can’t there be an infinite number of sentences constructed from words in a corpus?</li>
  <li>How can you embed paragraphs?</li>
  <li>Even if you used attention to update vector representations, how do you combine them?</li>
</ul>

<h2 id="pooling">Pooling</h2>

<p>You may have heard of pooling before in other ML contexts, particularly in Computer Vision where pooling refers to downsampling convolutional kernel output (aka feature maps). You perform pooling for a couple different reasons, primarily to:</p>
<ul>
  <li>Reduce dimensionality (makes computation faster)</li>
  <li>Promote translation invariance (makes network less sensitive to feature location)</li>
  <li>Abstract/Consolidate features (makes network focus on large patterns vs local details)</li>
</ul>

<p>In NLP pooling has a different meaning, but can be thought of in the same way as the CV case. Pooling is a method of converting a sequence of word embeddings into a singular embedding that represents primary features of the entire sequence (aka downsampling!). As opposed to Convolutional Neural Networks where pooling is applied after every convolution layer, NLP pooling is only applied at the very end of self-attention blocks. Sentence embeddings are just the output of the pooling operation on context-aware word embeddings (typically from the final attention layer/block).</p>

<p>Like in CV, there are different pooling methods that can be employed to get a representative embedding that captures the meaning of a sentence. The most common method is CLS pooling. In this method, a special classification token (usually called <CLS> or <s>) is appended to the beginning of every sentence/phrase/sequence of tokens the model is trained on. This token goes through the attention mechanism and is trained like how all other tokens would be (with the exception that the CLS token is never masked). Thus, it also has a representation that can be updated with contextually aware information. The CLS token is like the innocent bystander of the attention process - it is updated with relevant information but not necessarily apart of the sentence itself. Because of this, the representation of the CLS token has been chosen as a way to pool all of the word embeddings from a sentence. The idea is that the CLS token contains the same sentence level representation without being biased by any local semantics. A little more on BERT, the go-to language model for explaining/performing the state of the art, can be found [here]().</s></CLS></p>

<p>To go back to CV for a moment, this is a bit analogous to max pooling in the sense that there are other pooling options but research consistently uses one method. Some other methods for pooling in NLP include averaging all of the embeddings, taking the max value at every index across all embeddings, etc. I have not gone into full depth on if a particular pooling method is preferred for a particular usecase, but I suspect there wouldn’t be much of a difference (especially if the embedding is going to be fed into another neural network).</p>

<p>NOTE: Because attention (at its most basic form) is a context-aware weighted average, CLS pooling can be thought of as a weighted average of token embeddings. What’s nice is that the computation/weights for that average fall out naturally by virtue of passing text through the model.</p>

<p>NOTE: Not every language model has a CLS token with its pre-training objective, so if you care to know the behind the scenes on how the model you are using does its embedding I would suggest reading through HuggingFace/architecture diagrams.</p>

<h2 id="answers-to-my-previous-qualms">Answers to my previous qualms</h2>
<ol>
  <li>Can’t there be an infinite number of sentences constructed from words in a corpus?</li>
</ol>

<p>Technically yes if we define a sentence to be a length-unrestricted sequence of words (tokens). I can see the confusion where the thought process is “there are an infinite number of combinations so how can an infinite combination fit in one embedding space”. My counter to that is unlike word embeddings, they do not all sit in one space. There is no sentence embedding space like words, it is more so sentence embeddings are a function of embeddings that live in the word embedding space. That function is the pooling operation and it is dependent on the model you are getting embeddings from.</p>

<ol>
  <li>How can you embed paragraphs?</li>
</ol>

<p>Same way you would a sentence (aka pooling). A period (what delimits sentences from each other) is just a token, there is nothing special about it from the perspective of a language model. Assuming the paragraph you want to embed is not larger than the context limit of the language model you are passing it to, the process would be the exact same for a singular sentence.</p>

<ol>
  <li>Even if you used attention to update vector representations, how do you combine them?</li>
</ol>

<p>Depends on the pooling method you choose. The default method (most common) is just to take the embedding of the classification token (usually <cls> or <s>) from a sequence. The idea is that the classification token captures all of the relevant sequence level information and it's embedding is updated just like the rest of the word embeddings. Another technique is to average the embeddings of all the words in the sentence. There is no consensus on which method to choose, but for models trained on classification tasks its best to just use the cls representation.</s></cls></p>]]></content><author><name></name></author><category term="advanced" /><category term="NLP" /><category term="GenAI" /><summary type="html"><![CDATA[What does it mean to embed a sentence?]]></summary></entry><entry><title type="html">Exploring LLM uncertainty</title><link href="https://esoba.github.io/blog/2024/exploring-llm-uncertainty/" rel="alternate" type="text/html" title="Exploring LLM uncertainty" /><published>2024-02-26T09:00:10-08:00</published><updated>2024-02-26T09:00:10-08:00</updated><id>https://esoba.github.io/blog/2024/exploring-llm-uncertainty</id><content type="html" xml:base="https://esoba.github.io/blog/2024/exploring-llm-uncertainty/"><![CDATA[<blockquote>
  <p>Work in progress. These notes will be updated as I learn more.</p>
</blockquote>

<h2 id="intro">Intro</h2>

<p>Large Language Models (LLMs) are able to generate content by sampling from a learned probability distribution over possible next tokens. Even though modern LLMs have been trained on trillions of words (tokens) and have billions of parameters, there is no real guarentee on an LLMs output. To date, there is no way to fully measure how certain an LLM output is besides human verification. If we can understand what makes an LLM certain/uncertain in its output, it would have huge implications not only for LLM applications, but also for the publics trust in AI as a whole. Below, I’ll explore some concepts and why this is such a hard problem.</p>

<h2 id="quick-note">Quick Note</h2>
<p>There is a bunch of research into ML model uncertainty and I won’t be able to cover it all in this post. When doing research into this topic, I fell into countless rabit holes covering many areas related to probability theory and its role in Machine Learning. If you are like me and enjoy that deep dive into pure fundamentals, I think this <a href="https://www.gatsby.ucl.ac.uk/~balaji/balaji-uncertainty-talk-cifar-dlrl.pdf">slide deck</a> is a great place to start. I am also planning on doing a deep dive into Bayesian statistics and it’s role in ML so keep a look out for that!</p>

<p>Also, a majority of this post will be related to classification uncertainty since LLMs are auto-regressive token <em>classifiers</em>.</p>

<h2 id="what-exactly-is-uncertainty-in-ml">What exactly is uncertainty in ML?</h2>
<blockquote>
  <p>All models are wrong, but models that know when they are wrong, are useful.</p>
</blockquote>

<p>Uncertainty measures how much we can trust the predictions from a model. There are two types of uncertainty in ML:</p>
<ul>
  <li>epistemic: uncertainty from model (learned parameters)</li>
  <li>aleatoric: uncertainty from the data (stochasticity of observations)</li>
</ul>

<p>Epistemic is said to be reducible, meaning that in the presence of more data our model can do better at solving a given task. Assuming we had a model with infinite capacity (aka ability to learn any data pattern), our epistemic uncertainty would fall to 0 if we gave it infinite data. This is equivalent to saying if you overfit a model trained on every possible datapoint, you can always be certain your model will correctly classify that data. A model will have high epistemic uncertainty when looking at a datapoint that comes from a different distribution than the data it was trained on (and vice versa). This uncertainty can be measured by training multiple models on different subsets of data and measuring the variability of the predictions.</p>

<p>add little blurb on how to measure this type of uncertainty</p>

<p>For LLMs, epistemic uncertainty comes from not having seen enough content on a particular topic. For example, if I ask an LLM that has not been trained on arabic to translate a piece of text for me, it most likely will produce some bad output.</p>

<p>Aleatoric is irreducible, meaning that even in the presence of infinite data there will still be uncertainty in our predictions. This is due to the inherent randomness of data. Typically, observations/data we get from our environment will be noisy and we will not be able to know how that noise is distributed ahead of time. Because we cannot account for these perturbations, we have to accept that our model may be subject to data that is out of distribution (OOD) from its training data.</p>

<p>I think aleatoric is a little trickier to define for LLMs, but I like to think of it in terms of prompting. Prompts are our “input” to LLMs, so any vagueness or ambiguity will cause uncertainty to be high (even if we had a uber intelligent model). A question like “What am I wearing today?” would produce an answer with high uncertainty*. In general, random noise added to the prompt (ambiguity, typos, etc) can be considered alleatoric.</p>

<blockquote>
  <p>*NOTE: To be honest I read this example in a paper, but don’t know if I agree with it 100%. Conceptually, it makes sense if we assume just pure text completion training, but most LLMs are alligned (via RLHF, DPO, ORPO, etc.) to return an answer along the lines of “I don’t know how to answer that” (which is technically correct). I think that gets into a deeper philosophical question about an LLMs capability to understanding their limitations.</p>
</blockquote>

<p>When people refer to uncertainty without any particular label (like epistemic or aleatoric), they are typically referring to total uncertainty:</p>

<p>Total Uncertainty = Epistemic + Aleatoric</p>

<p>Uncertainty estimates fall into 4 categories:</p>
<ul>
  <li>Single deterministic methods: Measure uncertainty based single pass through model</li>
  <li>Ensemble methods: Measure uncertainty based on multiple models output</li>
  <li>Bayesian methods: Measure uncertainty based on stoachasticity of model</li>
  <li>Test time augmentation methods: Measure uncertainty by augmenting data</li>
</ul>

<p>Common evaluation metrics for uncertainty include:</p>
<ul>
  <li>Calibration: Measures the agreement between predicted probabilities and observed frequencies
    <ul>
      <li>Of all the times a model predicted class X with probability P, what fraction did we observe class X?</li>
    </ul>
  </li>
  <li>Log liklihood: Measures how well the model fit the data it was trained on</li>
  <li>Entropy: Measures how random/surprising a models predictions are</li>
</ul>

<p>Research in this space concerns itself with estimating the different types of uncertainty, and coming up with a total uncertainty measure that is representative of the task a particular model is trying to solve.</p>

<p>There are a couple things I think are important to note:</p>

<p>There is a difference between model uncertainty and model performance. Model performance considers the label output of the model compared to some known labels and uncertainty considers whether we should be asking the model to provide labels in the first place. Its the difference between saying “this image is a dog” and “I am 90% sure this is a dog”</p>

<p>The uncertainty you see from a models prediction are not always indicative of real life certainty. In fact, it has been shown models tend to be overconfident with their predictive probabilities. This is all to say that probabilities from a model alone are not enough to determine real world uncertainty. It is very possible for a model to be very confident in its prediction but in reality be completely wrong (especially when giving it OOD data).</p>

<h2 id="generation-makes-things-a-little-tricky">Generation makes things a little tricky</h2>

<p>I like to think of the generation task as a sequence of classifications or regressions (supervised tasks). For example, LLM text completions are sequences of auto-regressive token classifications, and image generations are sequences of pixel regressions. Generative ML makes uncertainty measures a little bit more difficult for a few different reasons:</p>
<ul>
  <li>Uncertainty can pop up in many different places in the sequence</li>
  <li>OOD is much harder to define</li>
  <li>Aggregating uncertainty across a sequence</li>
  <li>Generative models have an extraordinary large number of model parameters</li>
  <li>etc.</li>
</ul>

<h2 id="recap-of-llm-problem-setup">Recap of LLM problem setup</h2>
<p>LLMs are given an input prompt and generate an output sequence based on the instructions of the prompt. We consider the prompt a sequence of tokens $X = [x_1, x_2, … x_n]$, and the model returns another sequence of tokens $Y = [y1, y2, …y_m]$. The general decoding process is: $y_j = f([X, y_1, y_2, …])$. This means that the $j^{th}$ output token is a function of the prompt and the previously generated tokens. The function is itself the LLM that has learned to output a probability distribution over next possible tokens in a sequence.</p>

<p>The function is parameterized by the parameters of the ML model (underlying transformer architecture) and parameters of the sampling. The parameters of the ML model are fixed based on the pre-training the LLM provider had done, while the sampling parameters can be dictated by the user. These parameters include:</p>
<ul>
  <li>Temperature</li>
  <li>Top_p</li>
  <li>Top_k</li>
  <li>Max output tokens</li>
  <li>etc.</li>
</ul>

<p>What each of these parameters mean and how to effectively use those are included in another blog post.</p>

<h3 id="how-do-we-classify-ood-data-for-llms">How do we classify OOD data for LLMs</h3>
<p>OOD data for a classifier can be considered any input that does not belong to the predefined classes or deviates from the input distribution within those classes. For something like a dog vs cat classifier, OOD data could be a picture of a bird or a picture of a dog/cat its never seen before (for example, asking it to classify a chihuaha when it has only seen pictures of huskies).</p>

<p>For LLMs, the “does not belong to predefined classes” definition doesn’t hold up as well* because the LLM has been trained to see all types of tokens. Put another way, the vocabulary is finite and it has seen every token in the vocabulary. Thus, OOD data in this case refers more to knowledge than individual tokens. Prompting with information the model has never seen before (or has been aligned on), is considered OOD.</p>

<blockquote>
  <p>*Note: For the purposes of describing OOD data we’ll assume the LLM has been trained on the language it is being queried with. Asking an LLM that only knows English a question in Spanish would be considered OOD in the predefined classes sense, but we won’t consider that case because it is fairly rare.</p>
</blockquote>

<h2 id="why-cant-we-use-output-probabilities-to-measure-uncertainty">Why can’t we use output probabilities to measure uncertainty?</h2>

<p>Because LLMs output token probabilities, it would seem reasonable that the probability of a sequence would be a good proxy for uncertainty. Or, at the very least, there would be some meaningful way to combine token probabilities to make a good uncertainty metric. Let’s start with the simplest case: a single token output. Consider the following example (and assume True/False are 1 token):</p>

<p>Prompt: 
Given the following headline, determine if it is related to AI. Respond with only a true or false.</p>

<p>Headline:
Elon Musk sues OpenAI over mission statement</p>

<p>Answer:
True</p>

<p>This case is similar to classification: we have an input that maps to a singular output. To measure total uncertainty, we can calculate the total uncertainty using token level entropy. I am planning a blog post on information theories role in ML, where I will dive in a little bit deeper to what this all means. Presented informally, the token level probability for this particular sequence would be:</p>

<p>$H(t_{j}) = \sum \limits_{i=1}^m P(t_{j} = token_i)*\log P(t_{j} = token_i)$</p>

<p>Where $t_{j}$ is the token we are predicting a position $j$, and $token_i$ is the $i^{th}$ token in an LLMs vocabulary. In slightly less technical terms, this is considered the average “surprise” of observing $t_j$ as the value that it is. The maximum entropy would be the case where every token is just as likely aka $P(t_{j} = token_i) = \frac{1}{m}$ because there would be no indication that any token is favored over another. We can use this fact to normalize token level entropy to get a representative value between 0-1. Considering it is normalized by the maxium entropy (uncertainty), 0 would represent a deterministic output (aka completely certain) and 1 would represent uniform output (aka completely uncertain).</p>

<p>$H_{norm}(t_{j}) = \frac{H(t_{j})}{H_{max}}$</p>

<p>For the particular case above, the normalized entropy* is <em>__</em>. We can see that the value is close to 0, meaning the model is fairly certain its prediction!</p>

<p>Once we start to relax some of these assumptions, issues arise. First, let’s revise the prompt to let it know that we can accept the answers True, False, Yes, or No.</p>

<p>Prompt: 
Given the following headline, determine if it is related to AI. Respond with a single label that is either true, false, yes, or no.</p>

<p>Headline:
Elon Musk sues OpenAI over mission statement</p>

<p>Answer:
True</p>

<p>If we calculate the normalized token level entropy again, we get <em>__</em>. Even though we got the same answer from the LLM, it is more uncertain. This is because of semantics, and it is one of the main drivers for why uncertainty estimation is so difficult. Since True and Yes are both valid answers to the quesetion, the output token probability distribution is a lot more flat. We can see this below:</p>

<p>Insert picture of probablities here</p>

<p>This may seem like a contrived example, but imagine a scenario where instead of constraining the input to True, False, Yes, or No you asked something like “Give me a one word answer”. We would still see the same issue because many single words can answer the question. The point is that total uncertainty cannot be measured by entropy alone becuase there are many ground truth labels.</p>

<p>Let’s relax the assumption again and not constrain the output to being within a pre-defined set.</p>

<p>However, we cannot use that same confidence (probability) metric when we have an answer that is not constrained to a pre-defined set. Consider if the answer to the above question was instead something like:</p>

<p>Prompt: 
Given the following headline, determine if it is related to AI.</p>

<p>Headline:
Elon Musk sues OpenAI over mission statement</p>

<p>Answer:
“Yes, this article is related to AI”</p>

<p>Semantically, this is the same answer as the ones above. However, we now have multiple sources of uncertainty because there are multiple sequential predictions. One method we could do is find the token level entropies for each predicition and consolidate them to get some representative total uncertainty. For example:</p>
<ul>
  <li>Average across all tokens to get an average token level uncertainty,</li>
  <li>Take the max value to say “we are only as certain as our most uncertain token”</li>
  <li>etc.</li>
</ul>

<p>Doing this introduces more complications because:</p>
<ul>
  <li>Each aggregation would have tradeoffs</li>
  <li>Semantics are not well correlated with uncertainty</li>
  <li>Output sequence lengths are non-standard</li>
  <li>Only certain parts of a sequence are relevant for answering the prompt</li>
</ul>

<p>If we relax our problem completely to any arbitrary type of problem (not necessarily just classification) you can imagine OUR uncertainty in how to measure the models uncertainty gets bigger and bigger.</p>

<h3 id="does-asking-an-llm-to-rate-its-own-output-work">Does asking an LLM to rate its own output work?</h3>

<h3 id="what-evaluation-metrics-has-research-come-up-with">What evaluation metrics has research come up with?</h3>

<p>###</p>

<p>Sources 
https://arxiv.org/pdf/2307.10236.pdf
https://arxiv.org/pdf/2307.10236.pdf
https://www.watchful.io/blog/decoding-llm-uncertainties-for-better-predictability
https://cookbook.openai.com/examples/using_logprobs 
https://arxiv.org/pdf/2307.15703.pdf 
https://imerit.net/blog/a-comprehensive-introduction-to-uncertainty-in-machine-learning-all-una/</p>]]></content><author><name></name></author><category term="advanced" /><category term="NLP" /><category term="AI-Trust/Safety" /><category term="GenAI" /><summary type="html"><![CDATA[How much can we trust the output of an LLM?]]></summary></entry></feed>