<?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 Shrish on Medium]]></title>
        <description><![CDATA[Stories by Shrish on Medium]]></description>
        <link>https://medium.com/@Shrishml?source=rss-70b699ae9114------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Irwy3kTzWMOWcbV3UDQorg.jpeg</url>
            <title>Stories by Shrish on Medium</title>
            <link>https://medium.com/@Shrishml?source=rss-70b699ae9114------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:19:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Shrishml/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[All about Python AsyncIO]]></title>
            <link>https://medium.com/@Shrishml/all-about-python-asyncio-ca1f5a8974b0?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca1f5a8974b0</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 14:53:23 GMT</pubDate>
            <atom:updated>2025-04-25T06:02:03.605Z</atom:updated>
            <content:encoded><![CDATA[<h3>All about Python AsyncIO for GenAI developers</h3><p>If you are like me, you must be wondering what this “async” buzz is all about. Recently, we’ve seen a significant rise in asynchronous programming across modern applications. Initially, dragging my feet on learning it, I finally decided to take a closer look, and what a revelation it was. I was wondering why I did not know about it. This library has actually been part of Python’s ecosystem for over a decade, and fortunately, it is not nearly as complex as it might first appear. What is particularly exciting is how tremendously useful async programming has become, especially when building GenAI(Agents and all) applications, which most of us are involved with these days.</p><p>In this introductory article, I will start from first principles and build up your understanding step by step, covering only essential concepts you will need to get started.</p><h3>Why do we suddenly need Async?</h3><p>These days, with the rise of microservices and models as a service(OpenAI’s LLMs), we are seeing a lot of programs that call API endpoints and then simply wait for responses. Similarly, a lot of our code spends time writing to databases or files. These kinds of operations are classified as I/O operations (or I/O-bound operations), unlike CPU-bound operations, for example, running a machine learning model to give the predictions.</p><p>If you think about it fundamentally, when a client is performing I/O operations, it is not actively doing any computations; the CPU sits idle, waiting for data to arrive or confirm it was written. And we really hate idle compute resources! This is precisely where the async paradigm shines. The core idea is elegantly simple: we can run multiple I/O-bound (read: async) tasks concurrently and wait on all of them simultaneously. After all, if we are going to be waiting anyway, we might as well wait for multiple operations at once.</p><p>This approach makes particularly good sense in modern systems, where applications frequently need to coordinate with multiple services, databases, and external systems. Rather than blocking while waiting for each operation in sequence, async programming lets us maximize throughput by overlapping these waiting periods, ultimately reducing latency and delivering more responsive applications.</p><h3>Comparing Asynchronous Programming, Multithreading, and Multiprocessing</h3><p>If you are already here, you must have heard of multithreading and multiprocessing. I will take a short detour just for the sake of completeness — you can safely ignore this section. Asynchronous programming is very much like parallel programming, and since we’re on this topic, let’s see what other paradigms exist.</p><h4>Asynchronous Programming</h4><p>Asynchronous programming is ideal for I/O-bound operations like network calls and file operations. It uses single-threaded cooperative multitasking, where tasks voluntarily yield control at well-defined points. This approach provides excellent resource efficiency with very low overhead since everything runs in a single thread. The Python GIL(Global Interpreter Lock) doesn’t affect it negatively.</p><p><strong>Best for:</strong> Web scraping, chat applications, API orchestration, and network-heavy applications</p><p><strong>Advantages:</strong> Resource efficiency, no thread synchronization issues, excellent for waiting operations</p><p><strong>Limitations:</strong> Requires “async all the way down,” debugging challenges, and needs async-compatible libraries. All functions and the involved library should be async</p><p>An example can be a travel booking platform, which uses async programming to query dozens of airline, hotel, and car rental APIs simultaneously. This reduces search response times from potentially 10+ seconds (if done sequentially) to just 1–2 seconds, dramatically improving user experience while efficiently utilizing system resources.</p><h4>Multithreading</h4><p>Multithreading creates multiple execution paths within the same process that share memory. In Python, it’s limited by the Global Interpreter Lock (GIL), which prevents true CPU parallelism. Threads are preemptively scheduled by the operating system.</p><p><strong>Best for:</strong> I/O-bound operations with blocking code, GUI applications, database connection pools. Before async became popular in Python, we were using multithreading for the job.</p><p><strong>Advantages:</strong> Works with synchronous code, simpler conceptual model, good for mixing blocking and non-blocking operations.</p><p><strong>Limitations:</strong> Thread safety concerns, GIL limitations for CPU tasks, increased memory overhead</p><h4>Multiprocessing</h4><p>Multiprocessing launches separate processes, each with its own Python interpreter and memory space. This approach bypasses the GIL constraint, enabling true parallelism across CPU cores, but with higher communication costs. This is equivalent to running the same Python file in multiple terminals with different and independent data.</p><p><strong>Best for:</strong> CPU-bound computations like image processing, scientific simulations, machine learning, big data tasks</p><p><strong>Advantages:</strong> True parallelism across CPU cores, isolation prevents shared state issues</p><p><strong>Limitations:</strong> Higher memory usage, expensive process creation, complex inter-process communication, no shared memory among processes.</p><p><strong>Weather Forecasting Systems</strong>: Organizations like NOAA distribute massive computational workloads across thousands of processors, with each process handling different geographic regions or atmospheric layers. This CPU-intensive number crunching leverages true parallelism to generate complex weather models that would otherwise take too long to be useful.</p><h3>Understanding Python’s AsyncIO Library</h3><p>With preliminaries done, let’s jump to the actual library. The following examples aren’t exhaustive — they’re designed to convey the core concepts. There are many other interesting methods and functions in the library that you should explore if needed. But for most cases, what I’ll cover below will be enough to get you started.<br>As we go through these examples, remember that the goal is to understand the patterns and principles behind async programming, not to memorize every API detail. Once you grasp these fundamentals, you’ll find it straightforward to discover and apply more specialized features when your applications require them.</p><h4>Introduction to AsyncIO</h4><p>Python’s AsyncIO library provides a framework for writing single threaded concurrent code using coroutines(explaination upcoming). It serves as the foundation for asynchronous programming in Python, enabling efficient handling of many concurrent operations without the overhead of threads or processes.</p><h4>What is a Coroutine?</h4><p>A coroutine is a specialized function that can pause its execution at designated points, allowing other code to run, and later resume from where it left off. Think of it as a function that can have multiple entry and exit points.</p><p>Defining Coroutines with async def</p><pre># This is how you define a coroutine<br>async def fetch_data(url):<br>    print(f&quot;Starting to fetch data from {url}&quot;)<br>    # Simulate network delay<br>    await asyncio.sleep(2)<br>    print(f&quot;Finished fetching data from {url}&quot;)<br>    return f&quot;Data from {url}&quot;</pre><p>The async def Syntax tells Python this function is a coroutine. When called, it doesn&#39;t execute immediately but returns a coroutine object.</p><pre># This doesn&#39;t run the function, just creates a coroutine object<br>coro = fetch_data(&quot;https://example.com&quot;)<br>print(coro)  <br># Output: &lt;coroutine object fetch_data at 0x...&gt;</pre><p>This coroutine object is essentially a promise of future work. To actually execute it, we need to await it or schedule it with the event loop.</p><h4>Running Coroutines</h4><p><strong>Using </strong><strong>await Inside Another Coroutine</strong></p><p>The await keyword pauses the current coroutine until the awaited coroutine completes:</p><pre>async def main():<br>    # This pauses main() until fetch_data completes<br>    result = await fetch_data(&quot;https://example.com&quot;)<br>    print(f&quot;Result: {result}&quot;)<br>    return result</pre><p><strong>Running with </strong><strong>asyncio.run()</strong></p><p>To run a coroutine from synchronous code:</p><pre># This is the proper way to run the top-level coroutine<br>import asyncio<br><br># For Python 3.7+<br>result = asyncio.run(main())</pre><p><strong>Running in Jupyter Notebooks</strong><br>Jupyter notebooks require special handling as they already have an event loop:</p><pre># For Jupyter notebooks<br>import nest_asyncio<br>nest_asyncio.apply()<br><br># Now you can use asyncio.run() in notebooks<br>result = asyncio.run(main())<br><br># Alternatively, you can use this pattern:<br>await main()  # This works directly in notebook cells with IPython 7+</pre><h4>Creating and Managing Tasks</h4><p><strong>What is a Task?</strong></p><p>A task is a powerful abstraction that wraps around a coroutine, automatically scheduling it for execution on the event loop. Think of it as an independent unit of work that gains a life of its own once created, intelligently finding opportunities to progress whenever other coroutines pause during I/O operations or awaiting other results.</p><p>What makes tasks particularly powerful is their autonomy. When you create a task using asyncio.create_task(), you are essentially telling the event loop: &quot;Run this whenever you have a chance.&quot; The task then opportunistically executes during those small windows of time between other coroutines&#39; operations, maximizing CPU utilization that would otherwise be wasted.</p><pre>async def main():<br>    # Create a task<br>    task = asyncio.create_task(fetch_data(&quot;https://example.com&quot;))<br>    <br>    # Do other work while the task runs in the background<br>    print(&quot;Doing other work...&quot;)<br>    await asyncio.sleep(1)<br>    <br>    # Wait for the task to complete<br>    result = await task<br>    print(f&quot;Task result: {result}&quot;)</pre><p>At the end of your main coroutine, you have a choice: you can either gather the results of your tasks using await or asyncio.gather() If you need their return values, or you can simply let them complete on their own if the results aren&#39;t necessary. This flexibility makes tasks ideal for operations like logging, cache updates, or analytics that can safely run in the background without blocking your primary workflow.</p><p>By the way there are other cool methods related to task management, you can explore them if needed</p><ul><li><strong>task.cancel()</strong>: Requests cancellation of a task, useful for timeouts or user interruptions</li><li><strong>task.done()</strong>: Checks if the task has finished without blocking</li><li><strong>task.result()</strong>: Gets the return value (raises exception if not done)</li><li><strong>asyncio.wait_for()</strong>: Runs a coroutine with a timeout, cancelling if it takes too long</li><li><strong>asyncio.shield()</strong>: Protects a task from being cancelled by parent cancellations</li><li><strong>asyncio.gather()</strong>: Runs multiple tasks concurrently and collects all results</li><li><strong>asyncio.wait()</strong>: Waits for tasks with fine-grained control (first_completed, all_completed)</li><li><strong>asyncio.as_completed()</strong>: Returns tasks as they complete, not waiting for all</li><li><strong>task.add_done_callback()</strong>: Schedules a callback to run when task completes</li><li><strong>asyncio.current_task()</strong>: Gets the currently running task</li><li><strong>asyncio.all_tasks()</strong>: Gets all tasks in the event loop</li></ul><p>These methods give you precise control over task lifecycle, error handling, and coordination patterns.</p><h4>The Event Loop: Behind the Scenes</h4><p>The event loop is the central coordinator of all asynchronous operations in Python. Think of it as a ring master that keeps everything organized and running smoothly.</p><p><strong>What the Event Loop Does</strong></p><p>The event loop handles three main jobs:</p><ol><li><strong>Tracking Tasks</strong>: It keeps a list of all the coroutines and tasks that need to run.</li><li><strong>Deciding What Runs Next</strong>: When one task pauses, the event loop picks another one to continue.</li><li><strong>Managing I/O Operations</strong>: It watches for completed network requests, file operations, and other external processes.</li></ol><p><strong>How Tasks Take Turns</strong></p><p>When a coroutine uses await, it&#39;s telling the event loop: &quot;I need to wait for something, so I&#39;ll pause for now.&quot; The event loop then:</p><ol><li>Puts that coroutine on hold</li><li>Makes note of what it’s waiting for</li><li>Picks another coroutine that’s ready to run</li></ol><p>This passing back and forth happens automatically, letting multiple operations make progress without wasting time.</p><p><strong>The Loop’s Work Cycle</strong></p><p>The event loop works in a continuous cycle:</p><ol><li>Check if any waiting operations (like network requests) have finished</li><li>Run any coroutines that are now ready to continue</li><li>Check for new tasks that need to be scheduled</li><li>Repeat</li></ol><p>This cycle happens very quickly, giving the impression that everything is running at once, even though Python is actually working on one thing at a time.</p><pre>async def demonstrate_event_loop():<br>    # This visual example shows how coroutines take turns<br>    <br>    async def task1():<br>        print(&quot;Task 1: Starting&quot;)<br>        await asyncio.sleep(2)  # Yields control back to event loop<br>        print(&quot;Task 1: After 2 seconds&quot;)<br>        await asyncio.sleep(1)  # Yields control again<br>        print(&quot;Task 1: Finished&quot;)<br>    <br>    async def task2():<br>        print(&quot;Task 2: Starting&quot;)<br>        await asyncio.sleep(1)  # Yields control back to event loop<br>        print(&quot;Task 2: After 1 second&quot;)<br>        await asyncio.sleep(2)  # Yields control again<br>        print(&quot;Task 2: Finished&quot;)<br>    <br>    # Schedule both tasks to run concurrently<br>    # try commenting this gather line and run the code <br>    await asyncio.gather(task1(), task2())<br><br>import nest_asyncio<br>nest_asyncio.apply()<br><br><br><br># Alternatively, you can use this pattern:<br>await demonstrate_event_loop()  # <br><br># Output will show tasks interleaving their execution:<br># Task 1: Starting<br># Task 2: Starting<br># Task 2: After 1 second<br># Task 1: After 2 seconds<br># Task 2: Finished<br># Task 1: Finished</pre><h3>A dummy demo example</h3><p>Finally we are here to see the impact of async programming. This is what I was building up for.</p><p>The following code demonstrates an asynchronous workflow that mimics real-world scenarios in modern applications. It shows how to manage different types of I/O-bound operations (database writes, LLM API calls, and HTTP requests) using Python’s asyncio library. This example illustrates key concepts like dependent tasks (where we await results immediately) and background tasks (where we create tasks but don’t immediately wait for them). I will suggest you pull up one Jupyter notebook and copy these code snippets one by one in cells and run them to see for yourself.</p><pre>import asyncio<br>import time<br>import random<br><br># Store all events in a timeline for later analysis<br>async_timeline_events = []<br># Keep track of background tasks we&#39;ll gather at the end<br>tasks = []<br><br># Capture the start time to calculate relative timestamps<br>initial_timestamp = time.monotonic()<br><br>def log_event(timeline, task, event):<br>    &quot;&quot;&quot;<br>    Log an event with timestamp to visualize when operations start and end<br>    You can simply ignore this this does not serve any pupose in the pipeline.<br>    Args:<br>        timeline: List to append the event to<br>        task: Name/ID of the task<br>        event: Description of what happened (e.g., START or END)<br>    &quot;&quot;&quot;<br>    timestamp = time.monotonic() - initial_timestamp  # Calculate time since start<br>    timeline.append({<br>        &quot;task&quot;: task,<br>        &quot;event&quot;: event,<br>        &quot;timestamp&quot;: timestamp,<br>    })<br>    print(f&quot;[{timestamp:.2f}] {event}: {task}&quot;)<br><br><br>async def async_db_operation(step):<br>    &quot;&quot;&quot;<br>    Simulate a database write operation (like saving analytics or logs)<br>    <br>    In real applications, this would be writing data to a database,<br>    which is I/O-bound and benefits from asynchronous execution.<br>    &quot;&quot;&quot;<br>    task_id = f&quot;log_{step}&quot;<br>    log_event(async_timeline_events, task_id, &quot;START&quot;) # just logging time<br>    # Simulate variable database operation time<br>    await asyncio.sleep(random.uniform(0.3, 3.0))<br>    log_event(async_timeline_events, task_id, &quot;END&quot;) # just logging time<br><br>async def async_llm_call(prompt):<br>    &quot;&quot;&quot;<br>    Simulate a call to a Large Language Model API<br>    <br>    In real applications, this would be a network request to an API like<br>    OpenAI, Anthropic, or a self-hosted LLM service.<br>    &quot;&quot;&quot;<br>    task_id = f&quot;llm_{prompt[:10]}&quot;<br>    log_event(async_timeline_events, task_id, &quot;START&quot;) # just logging time<br>    # LLM calls often take longer than other API calls<br>    await asyncio.sleep(random.uniform(0.5, 3.2))<br>    log_event(async_timeline_events, task_id, &quot;END&quot;) # just logging time<br>    return f&quot;LLM result: {prompt}&quot;<br><br>async def async_http_call(endpoint):<br>    &quot;&quot;&quot;<br>    Simulate an HTTP request to an external API<br>    <br>    In real applications, this could be fetching data from a REST API,<br>    microservice, or other web service.<br>    &quot;&quot;&quot;<br>    task_id = f&quot;http_{endpoint.replace(&#39;/&#39;, &#39;&#39;)}&quot;<br>    log_event(async_timeline_events, task_id, &quot;START&quot;) # just logging time<br>    # Simulate variable network latency<br>    await asyncio.sleep(random.uniform(0.4, 4.0))<br>    log_event(async_timeline_events, task_id, &quot;END&quot;) # just logging time<br>    return f&quot;HTTP result from {endpoint}&quot;<br><br>async def run_async_pipeline():<br>    &quot;&quot;&quot;<br>    Main workflow that coordinates the execution of different async operations<br>    <br>    This demonstrates both:<br>    1. Dependent tasks (using &#39;await&#39;) - where we need results immediately<br>    2. Background tasks (using create_task) - where we can fire and forget<br>    &quot;&quot;&quot;<br>    log_event(async_timeline_events, &quot;main_pipeline&quot;, &quot;START_PIPELINE&quot;)<br><br>    # DEPENDENT TASK: We need the LLM result before proceeding<br>    llm_result = await async_llm_call(&quot;What&#39;s the user intent?&quot;)<br>    # BACKGROUND TASK: Log the result to the database, but don&#39;t wait for it<br>    tasks.append(asyncio.create_task(async_db_operation(&quot;llm_result&quot;)))<br><br>    # DEPENDENT TASK: We need this HTTP result for our business logic<br>    http1 = await async_http_call(&quot;/api/data&quot;)<br>    # BACKGROUND TASK: Log this API call, but don&#39;t block on it<br>    tasks.append(asyncio.create_task(async_db_operation(&quot;http1&quot;)))<br><br>    # DEPENDENT TASK: We need this data too before proceeding<br>    http2 = await async_http_call(&quot;/api/details&quot;)<br>    # BACKGROUND TASK: Another non-blocking logging operation<br>    tasks.append(asyncio.create_task(async_db_operation(&quot;http2&quot;)))<br><br>    # DEPENDENT TASK: Generate a summary using the LLM with collected data<br>    summary = await async_llm_call(&quot;Summarize everything&quot;)<br>    # BACKGROUND TASK: Log the summary generation<br>    tasks.append(asyncio.create_task(async_db_operation(&quot;summary&quot;)))<br><br>    log_event(async_timeline_events, &quot;main_pipeline&quot;, &quot;END_PIPELINE&quot;)<br><br>    # Wait for all background tasks to complete before exiting<br>    # This ensures all logging operations finish properly<br>    # This will run without gathering all tasks as well, you can try<br>    await asyncio.gather(*tasks)<br><br><br># Fix for running asyncio in environments like Jupyter notebooks<br>import nest_asyncio<br>nest_asyncio.apply()<br><br># Reset the timer before starting<br>initial_timestamp = time.monotonic() <br><br>print(&quot;\n--- Running Async Pipeline ---\n&quot;)<br># Run the main async workflow<br>asyncio.run(run_async_pipeline())<br></pre><p><strong>Output</strong></p><pre>--- Running Async Pipeline ---<br><br>[0.00] START_PIPELINE: main_pipeline<br>[0.00] START: llm_What&#39;s the<br>[0.94] END: llm_What&#39;s the<br>[0.94] START: http_apidata<br>[0.94] START: log_llm_result<br>[1.56] END: http_apidata<br>[1.56] START: http_apidetails<br>[1.56] START: log_http1<br>[1.89] END: log_llm_result<br>[3.04] END: log_http1<br>[3.38] END: http_apidetails<br>[3.38] START: llm_Summarize <br>[3.38] START: log_http2<br>[5.23] END: llm_Summarize <br>[5.23] END_PIPELINE: main_pipeline<br>[5.23] START: log_summary<br>[5.63] END: log_http2<br>[6.70] END: log_summary</pre><h4>The same example with sync functions</h4><p>This code demonstrates the traditional synchronous approach to handling I/O-bound operations like database writes, LLM API calls, and HTTP requests. In contrast to the asynchronous version we saw earlier, this code executes each operation sequentially, waiting for it to complete before moving to the next one. This pattern is simpler to understand but can lead to significant inefficiencies in I/O-bound applications.</p><pre># Timeline to track events for visualization and analysis<br>sync_timeline_events = []<br># Capture start time for calculating relative timestamps<br>initial_timestamp = time.monotonic()<br><br>def sync_db_operation(step):<br>    &quot;&quot;&quot;<br>    Simulate a synchronous database write operation<br>    <br>    In real applications, this would be writing data to a database,<br>    but here we&#39;re blocking the entire program while it runs.<br>    &quot;&quot;&quot;<br>    task_id = f&quot;log_{step}&quot;<br>    log_event(sync_timeline_events, task_id, &quot;START&quot;)<br>    # Block the entire program during this &quot;database operation&quot;<br>    time.sleep(random.uniform(0.3, 3.0))<br>    log_event(sync_timeline_events, task_id, &quot;END&quot;)<br><br>def sync_llm_call(prompt):<br>    &quot;&quot;&quot;<br>    Simulate a synchronous call to a Large Language Model API<br>    <br>    In real applications, this would be waiting for a response from<br>    an AI service like OpenAI or Anthropic, completely blocking execution.<br>    &quot;&quot;&quot;<br>    task_id = f&quot;llm_{prompt[:10]}&quot;<br>    log_event(sync_timeline_events, task_id, &quot;START&quot;)<br>    # Block the entire program during this &quot;API call&quot;<br>    time.sleep(random.uniform(0.5, 3.2))<br>    log_event(sync_timeline_events, task_id, &quot;END&quot;)<br>    return f&quot;LLM result: {prompt}&quot;<br><br>def sync_http_call(endpoint):<br>    &quot;&quot;&quot;<br>    Simulate a synchronous HTTP request to an external API<br>    <br>    In real applications, this would be waiting for a network response,<br>    with the program doing nothing else during this time.<br>    &quot;&quot;&quot;<br>    task_id = f&quot;http_{endpoint.replace(&#39;/&#39;, &#39;&#39;)}&quot;<br>    log_event(sync_timeline_events, task_id, &quot;START&quot;)<br>    # Block the entire program during this &quot;network request&quot;<br>    time.sleep(random.uniform(0.4, 4.0))<br>    log_event(sync_timeline_events, task_id, &quot;END&quot;)<br>    return f&quot;HTTP result from {endpoint}&quot;<br><br>def run_sync_pipeline():<br>    &quot;&quot;&quot;<br>    Main workflow that coordinates operations in a strictly sequential manner<br>    <br>    Each operation completely blocks the program until it finishes,<br>    resulting in poor resource utilization and longer total execution time.<br>    &quot;&quot;&quot;<br>    log_event(sync_timeline_events, &quot;main_pipeline&quot;, &quot;START_PIPELINE&quot;)<br><br>    # Step 1: Make LLM call and wait for it to complete<br>    llm_result = sync_llm_call(&quot;What&#39;s the user intent?&quot;)<br>    # Step 2: Log the result and wait for logging to complete<br>    sync_db_operation(&quot;llm_result&quot;)<br><br>    # Step 3: Make first HTTP call and wait for it to complete<br>    http1 = sync_http_call(&quot;/api/data&quot;)<br>    # Step 4: Log the HTTP result and wait for logging to complete<br>    sync_db_operation(&quot;http1&quot;)<br><br>    # Step 5: Make second HTTP call and wait for it to complete<br>    http2 = sync_http_call(&quot;/api/details&quot;)<br>    # Step 6: Log the HTTP result and wait for logging to complete<br>    sync_db_operation(&quot;http2&quot;)<br><br>    # Step 7: Make final LLM call and wait for it to complete<br>    summary = sync_llm_call(&quot;Summarize everything&quot;)<br>    # Step 8: Log the summary and wait for logging to complete<br>    sync_db_operation(&quot;summary&quot;)<br><br>    log_event(sync_timeline_events, &quot;main_pipeline&quot;, &quot;END_PIPELINE&quot;)<br><br># Reset the timer before starting<br>initial_timestamp = time.monotonic()<br><br>print(&quot;\n--- Running Sync Pipeline ---\n&quot;)<br># Run the synchronous workflow<br>run_sync_pipeline()</pre><p><strong>Output</strong></p><pre><br>--- Running Sync Pipeline ---<br><br>[0.00] START_PIPELINE: main_pipeline<br>[0.00] START: llm_What&#39;s the<br>[2.36] END: llm_What&#39;s the<br>[2.36] START: log_llm_result<br>[3.60] END: log_llm_result<br>[3.60] START: http_apidata<br>[5.55] END: http_apidata<br>[5.55] START: log_http1<br>[7.48] END: log_http1<br>[7.48] START: http_apidetails<br>[11.12] END: http_apidetails<br>[11.12] START: log_http2<br>[12.36] END: log_http2<br>[12.36] START: llm_Summarize <br>[13.72] END: llm_Summarize <br>[13.72] START: log_summary<br>[16.16] END: log_summary<br>[16.16] END_PIPELINE: main_pipeline</pre><h4>Plotting results: to see is to belive</h4><p>Following code will plot the timeline_events we have collected for both of our examples, generating one plot for sync and another for async execution. Looking closely at these visualizations will reveal a lot about the asyncio library and specifically the inner workings of the event loop.</p><pre>import matplotlib.pyplot as plt<br>from collections import defaultdict<br># Do not worry about this function, just think this give nice plot for event timelines<br>def plot_timeline(events, title):<br>    task_labels = {<br>        &quot;main_pipeline&quot;: &quot;Pipeline Start/End&quot;,<br>        &quot;llm_What&#39;s the&quot;: &quot;LLM: Intent&quot;,<br>        &quot;log_llm_result&quot;: &quot;Log: LLM result&quot;,<br>        &quot;http_apidata&quot;: &quot;HTTP1: /api/data&quot;,<br>        &quot;log_http1&quot;: &quot;Log: http1 result&quot;,<br>        &quot;http_apidetails&quot;: &quot;HTTP2: /api/details&quot;,<br>        &quot;log_http2&quot;: &quot;Log: http2 result&quot;,<br>        &quot;llm_Summarize &quot;: &quot;LLM: Summary&quot;,<br>        &quot;log_summary&quot;: &quot;Log: final summary&quot;<br>    }<br>    segments = defaultdict(lambda: {&quot;start&quot;: None, &quot;end&quot;: None})<br>    task_order = []<br>    seen = set()<br><br>    for event in events:<br>        task = event[&quot;task&quot;]<br>        if task not in seen:<br>            seen.add(task)<br>            task_order.append(task)<br>        if event[&quot;event&quot;] == &quot;START&quot; or event[&quot;event&quot;] == &quot;START_PIPELINE&quot;:<br>            segments[task][&quot;start&quot;] = event[&quot;timestamp&quot;]<br>        elif event[&quot;event&quot;] == &quot;END&quot; or event[&quot;event&quot;] == &quot;END_PIPELINE&quot;:<br>            segments[task][&quot;end&quot;] = event[&quot;timestamp&quot;]<br><br>    segments_labeled = [(task_labels.get(task, task), seg) for task, seg in segments.items()]<br>    segments_labeled = list(reversed(segments_labeled))<br><br>    fig, ax = plt.subplots(figsize=(12, 6))<br>    for i, (label, seg) in enumerate(segments_labeled):<br>        start, end = seg[&quot;start&quot;], seg[&quot;end&quot;]<br>        if start is not None and end is not None:<br>            ax.hlines(i, start, end, colors=&quot;blue&quot;, linewidth=1)<br>            ax.plot(start, i, &quot;g&gt;&quot;, markersize=5)<br>            ax.plot(end, i, &quot;r&lt;&quot;, markersize=5)<br><br>    ax.set_yticks(range(len(segments_labeled)))<br>    ax.set_yticklabels([label for label, _ in segments_labeled])<br>    ax.set_xlabel(&quot;Time (seconds)&quot;)<br>    ax.set_title(title)<br>    ax.grid(True)<br>    plt.tight_layout()<br>    plt.show()<br><br><br>plot_timeline(async_timeline_events, &quot;Async Task Timeline&quot;)<br>plot_timeline(sync_timeline_events, &quot;Sync Task Timeline&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-mX5Y4prNOSW_i-XG_x5Q.png" /><figcaption>Plotting event timeline for async tasks. Notice how tasks are running in parallel and interleaved among other tasks.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orko5wJch7efoJ44N8HHXg.png" /><figcaption>Plotting event timeline for sync tasks. All tasks are running in sequence,e one after another, taking more time than asynchronous ones</figcaption></figure><h4>Async vs Sync: The Numbers Don’t Lie</h4><p>Seeing the actual timing data makes all the difference in understanding why async programming matters. Looking at the execution logs, the results are crystal clear.</p><p>The async pipeline wrapped up everything in just 6.70 seconds, while the sync version dragged on for 16 seconds(some variation can come due to random numbers as well, but you get the point). And this is just a simple example — in real-world applications with dozens of API calls and database operations, this difference compounds dramatically.</p><p>What I want to point out is how operations overlap in the async timeline. Notice how at the 0.94s mark, the first LLM call finishes and immediately kicks off both an HTTP request and a database logging operation simultaneously. This efficient interleaving continues throughout the execution. Meanwhile, the sync version plods along one operation at a time, with the CPU sitting idle during all those I/O waits.</p><p>In our timeline visualization, you would see the async execution as a dense, efficient pattern with multiple operations stacked in parallel, while the sync version looks like a simple, stretched-out sequence with lots of wasted time.</p><p>The main pipeline itself (excluding some background tasks) finished in just 5.23 seconds with async, compared to 16 seconds for the sync approach.</p><h4>Explore More Resources</h4><p>Here are some additional insights and resources to take your understanding to the next level.</p><p>The Python asyncio ecosystem is rich and continuously evolving. To dive deeper:</p><p>The <a href="https://docs.python.org/3/library/asyncio.html">official asyncio documentation</a> is surprisingly approachable and comprehensive. It covers everything from basic coroutines to more advanced patterns like queues, synchronization primitives, and subprocess management.</p><p><a href="https://realpython.com/async-io-python/">Real Python’s async guide</a> offers one of the most practical, hands-on introductions you’ll find.</p><h4>Limitations and Challenges</h4><p>While async programming is powerful, it’s not without its challenges:</p><p><strong>The “Async All the Way Down” Problem</strong></p><p>One frustrating limitation is that you can’t mix synchronous and asynchronous code freely. Once you start using async, your entire call stack typically needs to support it. If you call a synchronous function that performs blocking I/O from an async function, you’ll block the entire event loop — defeating the purpose of using async in the first place.</p><pre>async def get_user_data():<br>    # This blocks the entire event loop despite being in an async function!<br>    results = requests.get(&quot;https://api.example.com/users&quot;)  # Blocking!<br>    return results.json()</pre><p>Instead, you need to use async-compatible libraries:</p><pre>async def get_user_data():<br>    async with aiohttp.ClientSession() as session:<br>        async with session.get(&quot;https://api.example.com/users&quot;) as response:<br>            return await response.json()</pre><p>Thanks for your time. I hope this helped you develop an understanding of asynchronous programing with asyncio library.</p><p>If you enjoyed the article, I invite you to follow me for future content. Additionally, feel free to connect with me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca1f5a8974b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making our own code interpreter: making of a sandbox]]></title>
            <link>https://medium.com/@Shrishml/making-our-own-code-interpreter-part-1-making-of-a-sandbox-382da3339eaa?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/382da3339eaa</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[code-generation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 15:45:48 GMT</pubDate>
            <atom:updated>2024-09-08T09:43:58.256Z</atom:updated>
            <content:encoded><![CDATA[<p>Many of us have wondered how ChatGPT runs code safely in its environment. While we can’t be certain of the exact methods OpenAI uses, we can explore how to create a similar system with the same fundamental principles.</p><p>In this series of articles, we’ll build a system with the following capabilities:</p><ol><li><strong>Generate Code</strong></li><li><strong>Run Code Safely</strong></li><li><strong>Upload Data Files and Download Results</strong></li></ol><p>The first part — code generation — is already well-supported by models like OpenAI’s, which generate code based on prompts. We’ll dive deeper into this later in the series. For now, we’ll focus on the second and third aspects: running code safely and handling file uploads and downloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vuzCYfDJv7dEzlY3" /></figure><h3>Why do we need a sandbox?</h3><p>A sandbox, in its simplest form, is a safe, enclosed space where children can play without getting hurt. Similarly, in computing, a sandbox allows us to run potentially unsafe code in a controlled environment, preventing it from causing harm to the system.</p><p>Python provides a basic way to run code using the exec() function, which executes Python code given as a string. For example:</p><pre>exec(generated_code, global_variables, local_variables)</pre><p>Here, generated_code is the code you want to run, and global_variables and local_variables are dictionaries containing the variables available to the code. This is a simple way to run code, but it can be dangerous without proper safeguards, which is why we&#39;ll explore how to build a secure sandbox in this series.</p><p>Here is an example of how we can run code generated by LLM,</p><pre>import pandas as pd<br>import numpy as np<br><br># Define a DataFrame with random data outside of the exec block<br>df = pd.DataFrame(np.random.randn(5, 3), columns=[&quot;A&quot;, &quot;B&quot;, &quot;C&quot;])<br><br># Define the script to be executed<br>python_script = &#39;&#39;&#39;<br>import pandas as pd<br># Some local variables for demo purposes<br>local_var1 = 42<br>local_var2 = &quot;Hello, exec()&quot;<br>local_var3 = df[&quot;A&quot;].mean()<br>&#39;&#39;&#39;<br><br># Prepare an empty local namespace dictionary<br>local_namespace = {}<br><br># Execute the script using exec() with df passed as part of globals<br>exec(python_script, {&quot;df&quot;:df}, local_namespace)<br><br># Print the local variables stored in local_namespace<br>print(&quot;\nCaptured local variables after exec():&quot;)<br>for var, value in local_namespace.items():<br>    if not var.startswith(&#39;__&#39;):  # Ignore built-in variables<br>        print(f&quot;{var}: {value}&quot;)<br><br></pre><pre>############## Output #############################<br>Captured local variables after exec():<br>pd: &lt;module &#39;pandas&#39; from &#39;/Users/symphonyai/anaconda3/envs/pd_agent/lib/python3.11/site-packages/pandas/__init__.py&#39;&gt;<br>np: &lt;module &#39;numpy&#39; from &#39;/Users/symphonyai/anaconda3/envs/pd_agent/lib/python3.11/site-packages/numpy/__init__.py&#39;&gt;<br>local_var1: 42<br>local_var2: Hello, exec()<br>local_var3: -0.012990217992773223</pre><h4>Self-harming programs</h4><p>When generating and executing code, especially in a production environment, security is a top priority. Without proper safeguards, even simple code generation prompts could lead to severe issues if the system is compromised. For instance, if someone injects a prompt designed to delete critical files or shut down the system, it could cause significant disruptions.</p><p>Take the following examples of potentially harmful code:</p><pre>import os<br>os.system(&quot;sudo shutdown -h now&quot;)  # Shuts down the computer</pre><p>This script shuts down the computer that you running the program on.</p><pre>import os<br>import sys<br>import glob<br># Get the directory of the currently running script<br>current_directory = os.path.dirname(os.path.abspath(__file__))<br># Get all files in the directory<br>files = glob.glob(os.path.join(current_directory, &#39;*&#39;))<br># Delete each file<br>for file_path in files:<br>    try:<br>        os.remove(file_path)<br>        print(f&quot;Deleted: {file_path}&quot;)<br>    except Exception as e:<br>        print(f&quot;Error deleting {file_path}: {e}&quot;)</pre><p>This script deletes every file in the current directory, which could be catastrophic in the wrong context. Another example is code that deletes important Python packages python.</p><pre>import importlib.util<br>import shutil<br>import os<br>def delete_package(package_name):<br>    # Find the location of the package<br>    spec = importlib.util.find_spec(package_name)<br>    if spec is None:<br>        print(f&quot;Package {package_name} is not installed.&quot;)<br>        return<br><br># Get the directory of the package<br>    package_path = spec.submodule_search_locations[0]<br>    # Delete the package directory<br>    try:<br>        shutil.rmtree(package_path)<br>        print(f&quot;Successfully deleted the {package_name} package.&quot;)<br>    except Exception as e:<br>        print(f&quot;Error deleting the {package_name} package: {e}&quot;)<br># Example: Delete pandas<br>delete_package(&#39;pandas&#39;)</pre><p>Running this would remove essential packages like pandas, potentially breaking your entire codebase.</p><h3>Isolating the execution environment</h3><p>To prevent such disasters, we can create a sandbox — a separate, isolated environment — where code can be safely executed without risking the integrity of the main system.</p><p>The idea is to have two systems:</p><ol><li><strong>The Main System</strong>: Where we interact with the user or agent and manage all other tasks.</li><li><strong>The Sandbox System</strong>: A separate, isolated environment (like a VM, cloud instance, or a different computer) where the generated code is executed. This system is designed to run code independently and return the results to the main system without affecting it.</li></ol><h4>Communication</h4><p>To enable communication between these two systems, we’ll use an API call. The main system will send the generated code and necessary files to the sandbox system via a web address or port. The sandbox will run the code, and once the execution is complete, it will send the results back to the main system. This is similar to how OpenAI’s API operates.</p><h3><strong>Building a sandbox app</strong></h3><p>Now that we understand the importance of a secure sandbox, let’s dive into creating one. By the end of this guide, we should have a sandbox app running inside a Docker container, allowing us to safely execute code without risking the integrity of our main system. This guide is not just about building the sandbox app — though you can certainly pull the final image from Docker Hub if you wish — but also about understanding how FastAPI, Docker images, and containers work together. This knowledge is essential for data scientists and engineers, as modern engineering systems increasingly rely on Docker containers and APIs.</p><h4>Step 1: Set up the folder structure</h4><p>First, let’s create the following folder structure. We’ll start by creating all the files and leaving them empty for now; we’ll fill them in step by step</p><pre>WorkFolder<br>├── session.py<br>├── test_session_and_main.py<br>└── sandbox<br>    ├── requirements.txt<br>    ├── main.py<br>    └── Dockerfile</pre><h4>Step 2: Install dependencies</h4><p>Copy the following content into requirements.txt and then run the command below in your terminal after navigating to the sandbox folder:</p><pre># filename - requirements.txt<br>fastapi==0.112.0<br>pandas==2.2.2<br>uvicorn==0.30.6<br>numpy==2.0.1<br>python-multipart==0.0.9<br>requests==2.32.3<br>plotly==5.23.0</pre><p>To install the dependencies, run:</p><pre>pip install -r requirements.txt</pre><h4>Step 3: Create the FastAPI application</h4><p>Next, copy the following code into the main.py file:</p><pre># filename - main.py<br>from fastapi import FastAPI, HTTPException<br>from fastapi import UploadFile, File<br>from fastapi.responses import JSONResponse<br>import pandas as pd<br>from io import BytesIO<br>import json<br>import pickle<br><br># Instantiate FastAPI application<br>app = FastAPI()<br><br># Initialization of dictionaries to upload files and save results<br>df_dict = {}<br>result_dict = {}<br><br><br>@app.post(&quot;/uploadfile/{file_name}&quot;)<br>async def upload_file(file_name: str, file: UploadFile = File(...)):<br>    &quot;&quot;&quot;<br>    This function manages the upload of files. <br>    It saves the content of the file into a pandas dataframe <br>    into the df_dict dictionary<br>    &quot;&quot;&quot;<br>    # Read file content<br>    content =  await file.read()<br>    df = pd.read_csv(BytesIO(content))<br>    df_dict[file_name] = df<br>    <br>    return {&quot;message&quot;: f&quot;File {file_name} has been uploaded&quot;}<br><br>@app.get(&quot;/files/&quot;)<br>async def get_files():<br>    &quot;&quot;&quot;<br>    This function returns a list with the names of all uploaded files.<br>    &quot;&quot;&quot;<br>    return {&quot;files&quot;: list(df_dict.keys()) }<br><br>@app.get(&quot;/downloadfile/{file_name}&quot;)<br>async def download_file(file_name: str):<br>    &quot;&quot;&quot;<br>    This function manages the download of files. <br>    It returns the content of a specific file converted into a Json format.<br>    &quot;&quot;&quot;<br>    df = df_dict.get(file_name, pd.DataFrame())<br>    return JSONResponse(content=df.to_json(orient=&quot;records&quot;))<br><br>@app.post(&quot;/execute_code/&quot;)<br>async def execute_code(request_body: dict):<br>    &quot;&quot;&quot;<br>    This function manages the execution of Python code <br>provided by the user in the request body.<br>    In the end, it returns the results in a Json format.<br>    &quot;&quot;&quot;<br>    # Initialize local dictionary<br>    local_dict = {}<br>    code = request_body.get(&quot;code&quot;)<br>    try:<br>        exec(code, df_dict, local_dict)<br>        result_dict.update(local_dict)<br><br>        # Convert any non-json serializable items into string using str().<br>        # This is required to send the data back using api and we <br>        # can not send dataframes <br>        # directly back<br>        for k, v in local_dict.items():<br>            if isinstance(v, pd.DataFrame):<br>                local_dict[k] = v.to_json()<br>        local_dict = {k: str(v) if not isinstance(v, \<br>        (int, float, bool, str, list, dict, pd.DataFrame)) \<br>         else v for k, v in local_dict.items()}\<br>            <br>    except Exception as e:<br>        raise HTTPException(status_code=400, detail=str(e))<br><br>    # Serialize local_dict to a JSON-formatted string<br>    local_dict = json.dumps(local_dict)<br>    return local_dict<br><br>@app.get(&quot;/clear_state/&quot;)<br>async def clear_state():<br>    &quot;&quot;&quot;<br>    This function manages the reset of the dictionaries so <br>    that it does not intefares with previous uploaded files.<br>    &quot;&quot;&quot;<br>    df_dict.clear()<br>    result_dict.clear()<br>    return {&quot;message&quot;: &quot;State has been cleared&quot;}</pre><p>You might be wondering why we’re using FastAPI to execute code when we could just run it locally with the exec method. The answer is that we don&#39;t want to run potentially unsafe code on our own machines. Instead, we&#39;ll execute it on another system—like a separate machine or a container—so that any issues won&#39;t affect our main environment. FastAPI allows us to send code and data to this separate system and receive the results safely via an API.</p><p>To run this application, use the following command in your terminal:</p><pre>uvicorn main:app --host 0.0.0.0 --port 8000 --reload</pre><h4>Step 4: Create a python wrapper</h4><p>While you can use requests.post or requests.get directly to interact with the API, it&#39;s more elegant to create a Python wrapper that abstracts these calls into methods. Copy the following code into the session.py file:</p><pre># filename- session.py<br>import requests<br>import pandas as pd<br>from typing import Any<br>from io import StringIO<br><br>class CodeSession:<br>    def __init__(self, url: str) -&gt; None:<br>        self.url = url<br>    <br>    def upload_file(self, file_name: str, data: pd.DataFrame) -&gt; Any:<br>        data_str = data.to_csv(index=False)<br>        files = {&quot;file&quot;: StringIO(data_str)}<br>        return requests.post(f&#39;{self.url}/uploadfile/{file_name}&#39;, files=files).json()<br>    <br>    def get_files(self) -&gt; Any:<br>        return requests.get(f&#39;{self.url}/files/&#39;).json()<br>    <br>    def download_file(self, file_name: str) -&gt; pd.DataFrame:<br>        response = requests.get(f&#39;{self.url}/downloadfile/{file_name}&#39;).json()<br>        return pd.read_json(response)<br><br>    def execute_code(self, code: str) -&gt; Any:<br>        return requests.post(f&#39;{self.url}/execute_code/&#39;, json={&quot;code&quot;: code}).json()<br><br>    def clear_state(self) -&gt; Any:<br>        return requests.get(f&#39;{self.url}/clear_state/&#39;).json()</pre><p>This wrapper makes it easier to interact with the sandbox app in a Pythonic way, allowing you to focus on writing and testing your code without getting bogged down in API calls.</p><h4>Step 5: Testing the sandbox app</h4><p>To ensure that our FastAPI sandbox app is working correctly, we need to test it. Here’s how you can do that:</p><p>Copy the following code into a file named test_session_and_main.py</p><pre># filename test_session_and_main.py<br><br>import sys<br>from session import CodeSession<br>import pandas as pd<br><br># Get the port number from command-line arguments<br>if len(sys.argv) != 2:<br>    print(&quot;Usage: python test_session_and_main.py &lt;port&gt;&quot;)<br>    sys.exit(1)<br><br>port = sys.argv[1] # getting port number from system arguments <br>base_url = f&#39;http://127.0.0.1:{port}&#39;<br>session = CodeSession(base_url)<br><br># Prepare some sample data<br>data = pd.DataFrame({<br>    &#39;A&#39;: [1, 2, 3],<br>    &#39;B&#39;: [4, 5, 6]<br>})<br><br># Use the session to upload a file<br>upload_resp = session.upload_file(&#39;df&#39;, data)<br>print(&quot;Upload Response:&quot;, upload_resp)<br><br># Use the session to get the list of files<br>files = session.get_files()<br>print(&quot;Files in Sandbox:&quot;, files)<br><br># Use the session to download a file<br>downloaded_df = session.download_file(&#39;df&#39;)<br>print(&quot;Downloaded DataFrame:&quot;)<br>print(downloaded_df)<br><br># Use the session to execute some code on the server<br>result = session.execute_code(&quot;result = df[&#39;A&#39;].sum()&quot;)<br>print(&quot;Execution Result:&quot;, result)</pre><p>Execute the script by running(we need to go to the parent directory by using cd ..) :</p><pre><br>python test_session_and_main.py 8000</pre><p>This will interact with the FastAPI app running locally, and you should see output confirming that each operation — uploading, listing, downloading, and executing code — is working correctly.</p><p>By running this test, you’ll confirm that your FastAPI app is functioning as intended and is ready for further use or deployment.</p><h3><em>Detour- what is a container?</em></h3><p><em>A container is a lightweight, standalone, and executable software package that includes everything needed to run a piece of software: the code, runtime, system tools, libraries, and settings. Containers isolate software from its environment and ensure that it works uniformly despite differences in operating systems and underlying infrastructure.</em></p><h4><strong><em>Why is virtualization required?</em></strong></h4><p><em>Virtualization allows multiple operating systems or applications to run on a single physical machine by creating virtual versions of hardware, software, or storage. This is essential because it provides a way to isolate applications from one another, reducing the risk of conflicts and enhancing security.</em></p><h4><strong><em>Why is virtualization important for our case?</em></strong></h4><p><em>In our case, virtualization is crucial because we need to run potentially unsafe code. Without virtualization, running this code directly on your machine could lead to system crashes, data loss, or other severe issues. Virtualization, through containers, allows us to isolate the execution environment, ensuring that any harmful effects are contained within the virtual environment and do not affect your main system.</em></p><h4><strong><em>What is an image?</em></strong></h4><p><em>An image is a blueprint or a snapshot of a container. It contains everything needed to run an application, including the operating system, application code, libraries, and dependencies. Images are immutable, meaning once they are created, they don’t change. They can be stored and reused, ensuring consistency across different environments.</em></p><h4><strong><em>How is an image made and structured in layers?</em></strong></h4><p><em>A Docker image is made by writing a </em><em>Dockerfile, a script that contains a series of instructions for assembling an image. These instructions might include copying files, setting environment variables, and installing software packages. Each instruction in the </em><em>Dockerfile creates a new layer in the image. Layers are stacked on top of each other, and Docker caches these layers to speed up the build process. If any part of the image changes, only the affected layers are rebuilt, which saves time and resources.</em></p><h4><em>How does a container run an image?</em></h4><p><em>When you run a container, it creates an instance of an image. This means the container is a running version of the image, with its own file system, network interface, and process space, but it still shares the kernel of the host operating system. Containers are lightweight because they don’t need a full-fledged operating system; they only need the resources specified in the image layers.</em></p><h4><em>Using images in kubernetes pods</em></h4><p><em>Kubernetes is a powerful orchestration tool that manages containerized applications. It allows you to deploy, scale, and manage containers across a cluster of machines. A Pod in Kubernetes is the smallest and simplest unit that you can create or deploy. It can contain one or more containers, all sharing the same network and storage resources.</em></p><p><em>When you deploy an image in a Kubernetes Pod, Kubernetes schedules it on one of the cluster’s nodes, ensuring it has the necessary resources to run. If the container fails, Kubernetes can automatically restart it or even replace it with a new container based on the same image, providing robust scalability and reliability in production environments.</em></p><h4><em>Why move our FastAPI app to a container?</em></h4><p><em>We’ve created a FastAPI application with endpoints for uploading and downloading files, executing code, and clearing the state. However, we’re currently running this app on our local machine, which means we’re still vulnerable to the risks we discussed earlier.</em></p><p><em>To truly implement a secure sandbox, we need to package this FastAPI app into a container. A Docker container acts like a separate machine within your machine. Running potentially unsafe code in this container won’t harm your main system. Even if something goes wrong and the container gets corrupted, it’s easy to revive it by recreating it from the same image. Moreover, in production environments, there are automated systems to repair or replace damaged containers, ensuring minimal downtime and consistent performance.</em></p><h4>Step 6: Writing the Dockerfile</h4><p>A Dockerfile is essentially a recipe that tells Docker how to build an image for our application. Here’s the Dockerfile we’ll use for our sandbox app:</p><pre># filename - Dockerfile<br>FROM python:3.11-slim<br><br>WORKDIR /app<br>COPY requirements.txt requirements.txt<br>RUN pip3 install -r requirements.txt<br>COPY . .<br>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8080&quot;]</pre><p><strong>Breaking Down the Dockerfile:</strong></p><ul><li><strong>FROM python:3.11-slim</strong>: This line sets the base image as Python 3.11. The slim version is a minimal image that includes just the essentials, making it lightweight and efficient.</li><li><strong>WORKDIR /app</strong>: This creates and sets the working directory inside the container where all subsequent commands will be run.</li><li><strong>COPY requirements.txt requirements.txt</strong>: This copies the requirements.txt file from your local machine to the container.</li><li><strong>RUN pip3 install -r requirements.txt</strong>: This installs all the necessary Python packages listed in requirements.txt inside the container.</li><li><strong>COPY . .</strong>: This copies the rest of your application’s files into the container.</li><li><strong>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</strong>: This specifies the command to start the FastAPI app using Uvicorn, setting it to listen on port 8000 of the container.</li></ul><p>With this Dockerfile, we can create an image that contains our entire FastAPI app, fully self-contained and ready to run.</p><h4>Step 7: Building and running the image</h4><p>Now, let’s build the Docker image and run it in a container:</p><p><em>Note: In this setup, we are using </em><em>nerdctl, which is a command-line interface for containerd. Containerd is a lightweight container runtime that handles the low-level details of running and managing containers. I got this along with Rancher Desktop. Alternatively, you can use Docker, which provides a user-friendly interface for container management. </em><strong><em>If you’re using Docker Desktop instead of Rancher Desktop, you can replace </em></strong><strong><em>nerdctl with </em></strong><strong><em>docker in all the commands provided below.</em></strong></p><p><strong>Build the image(on navigating to sandbox folder):</strong></p><pre>nerdctl build -t code_session .</pre><p>This command creates an image named code_session based on the Dockerfile</p><p><strong>Run the container:</strong></p><pre>nerdctl run -d -p 8080:8080 --name sandbox code_session</pre><p>This command starts a container named sandbox from the code_session image. It maps port 8000 inside the container to port 8080 on your machine, allowing you to access the app at <a href="http://localhost:8080.">http://localhost:8080.</a></p><h4>Step 8: Monitoring the container</h4><p>If you want to see the logs or monitor what’s happening inside the container, you can use the following command</p><pre>nerdctl logs -f sandbox</pre><p>This will show you the real-time logs from the sandbox container.</p><h3>Directly pulling the image</h3><p>If you prefer not to build the image yourself, you can directly pull and run the pre-built image from Docker Hub:</p><p><strong>Pull the image:</strong></p><pre>nerdctl pull shrishml/code_session</pre><p><strong>Run the container:</strong></p><pre>nerdctl run -d --name sandbox -p 8080:8000 shrishml/code_session</pre><p>And that’s it! You now have a fully functional sandbox environment running safely inside a Docker container.</p><p>To test the FastAPI sandbox app, you can use the following command:</p><pre>python test_session_and_main.py 8080</pre><p>In this case, the port 8080 is used, which is connected to the port 8080 of the Docker container running your FastAPI app. This is different from the port 8000 where your FastAPI app might have been running locally before. Since you have now set up the app inside a container on port 8080, you can close any previous instances of the FastAPI app running on port 8000.</p><p>This command will interact with the FastAPI sandbox app inside the container, allowing you to test file uploads, downloads, and code execution through the specified port.</p><p>Thanks for your time. I hope this helped you develop an understanding of code interpreters in general and some intro to containers and APIs.</p><p>If you enjoyed the article, I invite you to follow me for future content. Additionally, feel free to connect with me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>.</p><p>You might like my other related articles,</p><ul><li><a href="https://medium.com/@Shrishml/emergence-6d3eb6a27cbb">Emergence</a></li><li><a href="https://medium.com/@Shrishml/breaking-the-gmemory-barrier-how-zero-revolutionizes-large-language-model-training-8e00d2e2f30a">Breaking the Memory Barrier: How ZeRO Revolutionizes Large Language Model Training</a></li><li><a href="https://medium.com/@Shrishml/lora-low-rank-adaptation-from-the-first-principle-7e1adec71541">LoRA: Low-Rank Adaptation from the first principle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=382da3339eaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A primer on AI Agents with LangGraph, understand all about it]]></title>
            <link>https://medium.com/the-algorithmic-minds/a-primer-on-ai-agents-with-langgraph-understand-all-about-it-0534345190dc?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/0534345190dc</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 14:29:57 GMT</pubDate>
            <atom:updated>2024-09-08T09:44:25.102Z</atom:updated>
            <content:encoded><![CDATA[<p>AI agents have captivated computer scientists and scriptwriters for decades. Remember Agent Smith from the Matrix or the ever-helpful Jarvis? Countless movies depict intelligent programs rebelling against humanity. Today, we will deep dive into the fundamentals of AI agents, exploring their components and terminology from the ground up. We will even build a (somewhat) intelligent agent capable of performing tasks — a feat that would be incredibly challenging with traditional rule-based programming.<br>Before we start, let’s see what Andrej Karpathy, former director and leading researcher at Tesla and OpenAI, has to say about agents.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfqVLjtvWgq8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfqVLjtvWgq8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfqVLjtvWgq8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/04f4452391ea450108f69500687494d0/href">https://medium.com/media/04f4452391ea450108f69500687494d0/href</a></iframe><p>Now, I hope you are enough inspired to build agents.</p><h4>An Era of Large Language Model(LLM)</h4><p>Large language models (LLMs) are powerful deep-learning models trained to predict the next word based on the surrounding context. By being trained on massive amounts of text data, LLMs have shown remarkable capabilities, even exhibiting what some consider emergent intelligence.</p><p>While true artificial intelligence might still be a distant horizon, advancements in LLMs represent a significant leap forward. However, it’s important to remember that LLMs are currently specialized in a few tasks, like conversation, and struggle with generalization.</p><p>One key limitation of LLMs is their stateless nature. They function as single API calls, processing all context and history within that specific request. LLMs don’t retain information from previous interactions. For example, ChatGPT’s apparent ability to remember past conversations likely stems from appending historical chats (or summaries) to each new prompt, creating the illusion of statefulness. Just keep this in mind, we will come back at this later in this article.</p><p>For the purposes of this discussion, let’s consider LLMs as black boxes that take questions and provide natural language responses. It’s crucial to reiterate that these models don’t retain information from past queries. Let us also appreciate that replicating such a black box using traditional rule-based programming would be virtually impossible.</p><h4>Building AI Agents</h4><p>There are four fundamental design patterns that form the building blocks of most agents. These patterns can be used independently, combined, or interwoven depending on the specific use case.</p><ol><li><strong>Planning:</strong> Effective planning is critical for all agents. It involves breaking down complex problems into smaller, more manageable steps that can be reasoned about using available tools. This requires the agent to have a working understanding of its environment and the tools at its disposal.</li><li><strong>Reflection:</strong> Agents learn and adapt by reflecting on the results and feedback received from their interactions with the environment. By analyzing these outcomes, the agent can adjust its approach or problem-solving strategies for future encounters.</li><li><strong>Tool Use:</strong> Unlike humans who can manipulate the physical world directly, LLMs (Large Language Models) often rely on external tools to interact with their environment. These tools allow them to perform actions beyond simple communication, much like how humans use tools to accomplish tasks in the real world.</li><li><strong>Multi-agent Collaboration:</strong> This emerging pattern involves dividing tasks among different types of agents, each specialized for a specific function. This collaborative approach mirrors human organizations where teams of experts in areas like HR, finance, and technology work together to achieve a common goal.</li></ol><p>An AI agent is built upon four key components:</p><ol><li><strong>Brain (Decision-Making):</strong> This component, often powered by Large Language Models (LLMs), acts as the agent’s “brain.” It analyzes the environment, interprets information, and formulates plans to achieve the agent’s goals.</li><li><strong>Memory:</strong> The agent’s memory stores crucial information gathered during operation. This data can include past experiences, environmental details, and learned patterns, all of which are used to inform future decisions.</li><li><strong>Workflow (Action Management):</strong> This component dictates the order and flow of the agent’s actions. Some constraints or rules are introduced within the workflow to ensure the agent operates reliably and achieves its goals efficiently.</li><li><strong>Tools:</strong> These are the external capabilities the agent can leverage to interact with the environment beyond simple communication. Tools allow the agent to perform actions and complete tasks in the real world.</li></ol><p>As we move forward, we’ll explore how each of these components can be implemented using Langgraph.</p><p>For now, we are good at managing memory and tool execution (openai function calling), but <strong>workflow</strong> remains a challenge. There are two main approaches:</p><ul><li><strong>Free-flowing LLM control:</strong> This lets the agent determine its own control flow, similar to function-calling and ReACT agents in Langchain. However, this approach has limitations as it deviates and takes relatively more time.</li><li><strong>Predefined control flow:</strong> This involves defining the workflow beforehand using structures like DAGs (Directed Acyclic Graphs) or cycles. While Langchain LCEL can handle DAGs with conditionals as well, it can not implement cycles. In Langgraph we can predefined complete workflow with conditional and cyclic components well, providing much flexibility to agents.</li></ul><p>More details on the topic can be found here in this rich blog.</p><p><a href="https://lilianweng.github.io/posts/2023-06-23-agent/">LLM Powered Autonomous Agents</a></p><h4>Hands-on Agents with LangGraph</h4><p>LangGraph simplifies AI agent development by focusing on three key components:</p><ol><li><strong>State:</strong> This represents the agent’s current information, often stored as a dictionary or managed through a database.</li><li><strong>Nodes:</strong> These are the building blocks that execute computations. They can be LLM-based, Python code, or even other Langgraph units (subgraphs). Nodes take the <strong>state</strong> as input, perform modifications, and return the updated <strong>state</strong>.</li><li><strong>Edges:</strong> Edges define the agent’s control flow. They dictate the specific path the agent follows, but Langgraph injects flexibility through <strong>conditional nodes, and cycles</strong>. These nodes allow the agent to adapt its course based on specific conditions met within the graph in the shared <strong>State</strong>.</li></ol><p>LangGraph’s strength lies in its ability to balance control flow with adaptability. Conditional nodes and the allowance of cycles empower agents to be both flexible and reliable. Similar to a finite state machine, each node takes the current state, performs modifications, and returns the updated state. Other nodes can then adapt their behavior based on the changes. However, a key advantage of LangGraph is that nodes can be “relatively intelligent” thanks to LLM integration. This reduces reliance on extensive rule-based programming, making agent development more efficient.</p><h4>An Agent that can do math</h4><p>Large Language Models (LLMs) are known to struggle with complex math problems. Their strength lies in predicting the next word in a sequence, not performing calculations directly. To address this limitation, we’ll utilize LangGraph to equip our agent with custom math tools, extending its capabilities.</p><p>These tools and the agent itself serve as a demonstration of LangGraph’s power in building intelligent agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*62gIP4w1O6VGQ2BDDHNB_Q.png" /><figcaption>The agent’s workflow follows a logical loop. It starts with planning, where it figures out the tools and arguments needed to solve the problem. Then, it executes those tools using LangGraph nodes. After execution, a conditional node decides if more planning is required based on the outcome. If so, the loop restarts. If not, the agent generates a final response for the user through a responder node. This design highlights LangGraph’s ability to build adaptable agents that can iteratively plan and execute tasks.</figcaption></figure><pre>import os<br>from dotenv import load_dotenv<br>from pathlib import Path<br>dotenv_path = Path(&#39;.env&#39;)<br>load_dotenv(dotenv_path=dotenv_path</pre><p>This code snippet is on setting up essential environment variables for this notebook. We only require two variables: the OpenAI API key and the deployment name for the LLM we’ll be using. We need to save all environment variables in a file named .env.</p><pre><br>import pandas as pd<br><br>from langchain.tools import tool<br><br>@tool<br>def addition(x, y):<br>    &quot;&quot;&quot;Addition of two number<br>    :param: x: The first number to be added <br>    :param: y: The second number to be added&quot;&quot;&quot;<br><br>    return x+y<br><br>@tool<br>def subtraction(x, y):<br>    &quot;&quot;&quot;Sumbtration of two number<br>    :param: x: The first number the greater one  <br>    :param: y: The second number to be subtracted &quot;&quot;&quot;<br><br>    return x-y<br><br>@tool<br>def multiplication(x, y):<br>    &quot;&quot;&quot;Multiplication of two number<br>    :param: x: The first number to be multiplied <br>    :param: y: The second number to be multiplied&quot;&quot;&quot;<br><br>    return x*y<br><br>@tool<br>def division(x, y):<br>    &quot;&quot;&quot;Division of two number<br>    :param: x: The first number the greater one  <br>    :param: y: The second number to be devided &quot;&quot;&quot;<br><br>    return x/y<br><br>tools = [addition, subtraction, multiplication, division]<br><br>tool_dict =  {} # this is going to be required during tool execution<br><br>for tool in tools:<br>    tool_dict[tool.name]= tool</pre><p>The code we’ve seen defines a set of simple tools using Python functions. Each tool’s docstring explains its purpose, and the parameters section details the expected inputs. These tools will empower the LLM (Large Language Model) to make informed decisions as it strives to answer user queries.</p><p>To simplify tool execution, a dictionary named tool_dict has been created. This dictionary allows us to call the tool functions by their names during the execution phase. Notably, we&#39;re leveraging Langchain&#39;s tool decorator, which seamlessly integrates these custom tools into the LLM&#39;s available functions.</p><pre>import json<br>from langchain_core.prompts import ChatPromptTemplate<br>from langgraph.graph import StateGraph, END<br>from typing import TypedDict, List, Annotated<br>from typing import List, Optional<br>from langchain_openai import AzureChatOpenAI<br>from langchain.output_parsers.openai_tools import JsonOutputToolsParser<br>import operator<br>import os <br>from loguru import logger<br><br>class StrategyAgentState(TypedDict):<br>    user_query: str<br>    steps: Annotated[List, operator.add]<br>    step_no: int<br>    results: dict<br>    final_response: str<br>    end:bool</pre><p>As discussed earlier, LangGraph operates on graphs consisting of nodes and edges. Nodes act as the computational units. They receive the current state as input, perform modifications, and return the updated state. Think of the state as an equivalent to a Python dictionary.</p><p>Careful state definition is crucial. Include fields that will be valuable during orchestration, anticipating future needs. Here’s a breakdown of some key state variables:</p><ul><li>user_query: This field stores the question the user has posed to the agent.</li><li>steps: This list holds the tasks identified by the planner node that need to be executed by the tool execution node.</li><li>step_no: This counter, maintained by the tool executor node, prevents redundant task execution.</li><li>results: This field acts as a temporary storage for intermediate results generated by the tools.</li><li>final_response: As the name suggests, this variable holds the final answer that will be delivered to the user.</li><li>end: This field is updated by the planner or tool executor nodes. It indicates whether all steps have been completed, signifying the end of the workflow.</li></ul><p>Above is my simple design to make this toy agent. You can be really creative in designing states and using them during orchestration.</p><pre>deployment_name = os.environ[&quot;AZURE_DEPLOYMENT&quot;]<br>azure_endpoint = os.environ[&quot;AZURE_ENDPOINT&quot;]<br>api_key = os.environ[&quot;AZURE_API_KEY&quot;]<br>api_version = os.environ[&quot;API_VERSION&quot;]<br><br>llm = AzureChatOpenAI(azure_deployment=deployment_name,<br>                            azure_endpoint=azure_endpoint,<br>                            api_key=api_key,<br>                            api_version=api_version, temperature=0.0)<br><br>def plan(state: StrategyAgentState):<br>    &quot;&quot;&quot;The planner node, this is the brain of the system&quot;&quot;&quot;<br>    user_question = state[&quot;user_query&quot;]<br>    steps = state[&quot;steps&quot;]<br>    results = state[&quot;results&quot;]<br>    end = state[&quot;end&quot;]<br><br>    if results is None:  # If result has not been populated yet we will start planning <br>        SYSTEM_PROMT = &quot;You are a helpful assitant who is good is mathematics.\<br>            Do not calculate yourself let the tool do the calculation. Call one tool at a time&quot;<br>        prompt_template = ChatPromptTemplate.from_messages(<br>                        [(&quot;system&quot;, SYSTEM_PROMT),<br>                        (&quot;user&quot;, &quot;{user_question}&quot;)])<br><br>        planner = prompt_template | llm.bind_tools(tools)| JsonOutputToolsParser()<br><br>    <br><br>        invoke_inputs = {&quot;user_question&quot;: user_question}<br>        steps = planner.invoke(invoke_inputs)<br><br>        logger.info(f&quot;Generated plans : {steps}&quot;)<br><br>        return {&#39;steps&#39;: steps}<br>    elif results and not end: # If result has been populated and end is not true we will go to end detector<br>        SYSTEM_PROMT = &quot;You need to decide whether a problem is solved or not. Just return ##YES if propblem is solved and ##NO \<br>        if problem is not solved. Please expalain your reasoning as well. Make sure you use same template of ##YES and ##NO in final answer.\<br>         Do not calculate yourself let the tool do the calculation&quot;<br>        prompt_template = ChatPromptTemplate.from_messages(<br>                        [(&quot;system&quot;, SYSTEM_PROMT),<br>                        (&quot;user&quot;, &quot;{user_question}&quot;), <br>                        (&quot;user&quot;, &quot;{results}&quot;),<br>                        (&quot;user&quot;, &quot;{steps}&quot;)])<br><br>        planner = prompt_template | llm<br><br>    <br><br>        invoke_inputs = {&quot;user_question&quot;: user_question, &quot;steps&quot;:json.dumps(steps), &quot;results&quot;:json.dumps(results)}<br>        response = planner.invoke(invoke_inputs)<br><br>        logger.info(f&quot;End detector response : {response.content}&quot;)<br><br>        if  &quot;##YES&quot; in response.content:<br>            return {&#39;end&#39;: True}<br>        elif &quot;##NO&quot; in response.content:<br>            return {&#39;end&#39;: False}<br>    else: # if end is not true and <br>        SYSTEM_PROMT = &quot;You are a helpful assitant who is good is mathematics.\<br>              You are replanner assistant.\<br>        If you are given previous steps and previous results. Do not start again. Call one function at a time.\<br>             Do not calculate yourself let the tool do the calculation&quot;<br>        prompt_template = ChatPromptTemplate.from_messages(<br>                        [(&quot;system&quot;, SYSTEM_PROMT),<br>                        (&quot;user&quot;, &quot;{user_question}&quot;), <br>                        (&quot;user&quot;, &quot;{steps}&quot;),<br>                        (&quot;user&quot;, &quot;{results}&quot;)])<br><br>        planner = prompt_template | llm.bind_tools(tools)| JsonOutputToolsParser()<br><br>    <br><br>        invoke_inputs = {&quot;user_question&quot;: user_question, &quot;steps&quot;:json.dumps(steps), &quot;results&quot;:json.dumps(results)}<br>        steps = planner.invoke(invoke_inputs)<br><br>        logger.info(f&quot;Pending  plans : {steps}&quot;)<br><br>        return {&#39;steps&#39;: steps}</pre><p><strong>The Planner Node: Orchestration Efficiency</strong></p><p>While the planner node appears complex, its core functionalities are designed for efficiency. It acts as the maestro of the orchestration process, taking on three key roles:</p><ol><li><strong>Initiation Planning:</strong> At the beginning of the workflow, the planner crafts an initial plan outlining the steps the agent needs to take to address the user’s query. This plan is stored in the state variable, which is a list.</li><li><strong>Adaptive Planning:</strong> As the workflow progresses, the planner can dynamically update the plan based on two factors: intermediate results and past plans. This adaptability allows the agent to react to unforeseen circumstances and refine its approach as needed. When the planner returns the steps list, it efficiently adds new steps to the existing list instead of overwriting everything.</li><li><strong>Completion Signal:</strong> Finally, the planner plays a crucial role in declaring the end of the plan. It analyzes intermediate results and past plans to determine if all necessary steps have been completed. If so, the planner simply updates the end field in the state to True, signaling the workflow&#39;s completion.</li></ol><p>An important aspect of LangGraph&#39;s efficiency is its ability to selectively update the state. Instead of returning the entire state after each modification, the node can focus on just the specific fields that have been changed.</p><p>LangGraph achieves this through annotations within the state definition. These annotations specify how updated data should be incorporated into the existing state. For example, the steps field is annotated with operator.add. This instructs LangGraph to efficiently append new steps to the existing list, rather than overwriting the entire list with each update.</p><p>In contrast, for fields without annotations like operator.add, returning a dictionary with the updated value will simply overwrite the existing data in that field.</p><pre><br><br><br>def tool_execution(state: StrategyAgentState):<br><br>    &quot;&quot;&quot; Worker node that executes the tools of a given plan. Plan is json arguments<br>    which can be sent to tools directly&quot;&quot;&quot;<br><br>    steps = state[&quot;steps&quot;]<br>    step_no = state[&quot;step_no&quot;] or 0<br><br><br>    _results = state[&quot;results&quot;] or {}<br>    j= 0<br>    for tool in steps[step_no: ]:<br><br>        tool_name = tool[&#39;type&#39;]<br>        args = tool[&quot;args&quot;]<br>        _results[tool_name+&quot;_step_&quot;+str(step_no+j)] = tool_dict[tool_name](args)<br>        logger.info(f&quot;{tool_name} is called with arguments {args}&quot;)<br>        j=j+1<br><br>    return {&quot;results&quot;: _results, &quot;step_no&quot;: step_no+j, }<br><br>def responder(state:StrategyAgentState):<br><br><br>    user_question = state[&quot;user_query&quot;]<br>    results = state[&quot;results&quot;]<br>    SYSTEM_PROMT = &quot;Generate final response by looking at the results and original user question.&quot;<br>    prompt_template = ChatPromptTemplate.from_messages(<br>                    [(&quot;system&quot;, SYSTEM_PROMT),<br>                     (&quot;user&quot;, &quot;{user_question}&quot;),<br>                     (&quot;user&quot;, &quot;{results}&quot;)])<br><br>    model = prompt_template | llm<br><br> <br><br>    invoke_inputs = {&quot;user_question&quot;: user_question, &quot;results&quot;: json.dumps(results)}<br>    response = model.invoke(invoke_inputs)<br>    return {&quot;final_response&quot;: response.content}<br><br><br></pre><p>These sections introduce two crucial nodes in our LangGraph workflow: the tool executor and the responder. The tool executor takes charge of executing the steps outlined in the steps field of the state. It processes these steps one by one, leveraging the custom tools we defined earlier. The results generated by each tool execution are stored as a dictionary within the results field of the state. It&#39;s important to note that this overwrites any existing results in the dictionary because it is not annotated.</p><p>Following the tool execution, the responder node steps in. Its role is to analyze all the intermediate results accumulated in the results field. By processing this data, the responder crafts a clear and informative response for the user. This final response is then placed in the final_response field of the state, ready to be delivered to the user.</p><pre>def route(state:StrategyAgentState):<br>    &quot;&quot;&quot;A conditional route based on number of steps completed or end anounced by any other node,<br>      this will either end the execution or will be sent to tools for planning&quot;&quot;&quot;<br><br>    steps = state[&quot;steps&quot;]<br>    step_no = state[&quot;step_no&quot;]<br>    end = state[&quot;end&quot;]<br>    if end:<br>        # We have executed all tasks<br>        return &quot;respond&quot;<br>    else:<br>        # We are still executing tasks, loop back to the &quot;tool&quot; node<br>        return &quot;plan&quot;<br></pre><p>The router node acts as a critical decision point within the workflow. It evaluates the end field in the state. If end is set to True, signifying that all necessary steps have been completed, the router returns respond as a string. This string represents the final answer that will be delivered to the user. However, if end remains False, indicating that more work is required, the router returns plan. We&#39;ll explore how LangGraph utilizes this information just in a while.</p><pre>graph = StateGraph(StrategyAgentState)<br>graph.add_node(&quot;plan&quot;, plan)<br>graph.add_node(&quot;tool_execution&quot;, tool_execution)<br>graph.add_node(&quot;responder&quot;, responder)<br>#--------------------------------------------------------<br>graph.add_edge(&quot;plan&quot;, &quot;tool_execution&quot;)<br>graph.add_edge(&quot;responder&quot;, END)<br>graph.add_conditional_edges(&quot;tool_execution&quot;, route, {&quot;respond&quot;:&quot;responder&quot;, &quot;plan&quot;:&quot;plan&quot;})<br>graph.set_entry_point(&quot;plan&quot;)<br>agent = graph.compile()</pre><p>While each node we’ve discussed acts as an independent computational unit, it can also operate concurrently as long as the state dictionary provides the necessary information. Now, it’s time to assemble these individual nodes into a cohesive workflow. This workflow dictates the order of node execution, ensuring a logical progression.</p><p>In the first code block, we defined each node by assigning a name and a corresponding Python function. The add_node method takes two arguments: the node&#39;s name and the associated Python function.</p><p>The second code block focuses on edge creation, establishing the connections between nodes. The add_edge method takes two arguments: the first node and the second node it connects to. Following this logic, the workflow transitions from the planner node to the tool execution node, as the plan needs to be established before tool execution begins. Similarly, the workflow proceeds from the responder node to the end node, signifying completion.</p><p>However, LangGraph’s true power lies in its concept of conditional edges. These edges allow us to dynamically route the workflow back to any previous node, potentially creating cycles. In our example, a conditional edge is established from the tool execution node back to the router node. This enables the router to make a decision based on the end field in the state. If end is True, indicating completion, the workflow progresses to the responder node. Conversely, if end is False, signifying more work is required, the workflow loops back to the planner node for further processing. I will again attach the figure of graph here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*62gIP4w1O6VGQ2BDDHNB_Q.png" /><figcaption>The agent’s workflow follows a logical loop. It starts with planning, where it figures out the tools and arguments needed to solve the problem. Then, it executes those tools using LangGraph nodes. After execution, a conditional node decides if more planning is required based on the outcome. If so, the loop restarts. If not, the agent generates a final response for the user through a responder node. This design highlights LangGraph’s ability to build adaptable agents that can iteratively plan and execute tasks.</figcaption></figure><pre>query = &quot;what is 3 multiplied by 9 added to 45 then devide all by 6&quot;<br><br><br>for s in agent.stream({&quot;user_query&quot;: query}):<br>    print(s)<br>    print(&quot;--------------------&quot;)<br></pre><p>Now, above is how we run the agent, and below is the output.</p><pre>2024-04-24 17:09:34.041 | INFO     | __main__:plan:71 - Generated plans : [{&#39;type&#39;: &#39;multiplication&#39;, &#39;args&#39;: {&#39;x&#39;: 3, &#39;y&#39;: 9}}, {&#39;type&#39;: &#39;addition&#39;, &#39;args&#39;: {&#39;x&#39;: 27, &#39;y&#39;: 45}}, {&#39;type&#39;: &#39;division&#39;, &#39;args&#39;: {&#39;x&#39;: 72, &#39;y&#39;: 6}}]<br>2024-04-24 17:09:34.053 | INFO     | __main__:tool_execution:145 - multiplication is called with arguments {&#39;x&#39;: 3, &#39;y&#39;: 9}<br>2024-04-24 17:09:34.054 | INFO     | __main__:tool_execution:145 - addition is called with arguments {&#39;x&#39;: 27, &#39;y&#39;: 45}<br>2024-04-24 17:09:34.055 | INFO     | __main__:tool_execution:145 - division is called with arguments {&#39;x&#39;: 72, &#39;y&#39;: 6}<br>{&#39;plan&#39;: {&#39;steps&#39;: [{&#39;type&#39;: &#39;multiplication&#39;, &#39;args&#39;: {&#39;x&#39;: 3, &#39;y&#39;: 9}}, {&#39;type&#39;: &#39;addition&#39;, &#39;args&#39;: {&#39;x&#39;: 27, &#39;y&#39;: 45}}, {&#39;type&#39;: &#39;division&#39;, &#39;args&#39;: {&#39;x&#39;: 72, &#39;y&#39;: 6}}]}}<br>--------------------<br>{&#39;tool_execution&#39;: {&#39;results&#39;: {&#39;multiplication_step_0&#39;: 27, &#39;addition_step_1&#39;: 72, &#39;division_step_2&#39;: 12.0}, &#39;step_no&#39;: 3}}<br>--------------------<br>2024-04-24 17:09:35.342 | INFO     | __main__:plan:93 - End detector response : ##YES<br><br>The correct calculation steps have been followed in the given order: <br>1. 3 multiplied by 9 equals 27<br>2. 27 added to 45 equals 72<br>3. 72 divided by 6 equals 12.0<br><br>Therefore, the final result is 12.0, which matches the provided result.<br>{&#39;plan&#39;: {&#39;end&#39;: True}}<br>--------------------<br>{&#39;tool_execution&#39;: {&#39;results&#39;: {&#39;multiplication_step_0&#39;: 27, &#39;addition_step_1&#39;: 72, &#39;division_step_2&#39;: 12.0}, &#39;step_no&#39;: 3}}<br>--------------------<br>{&#39;responder&#39;: {&#39;final_response&#39;: &#39;3 multiplied by 9 is 27. Adding 27 to 45 gives 72. Finally, dividing 72 by 6 results in 12.0.&#39;}}<br>--------------------<br>{&#39;__end__&#39;: {&#39;user_query&#39;: &#39;what is 3 multiplied by 9 added to 45 then devide all by 6&#39;, &#39;steps&#39;: [{&#39;type&#39;: &#39;multiplication&#39;, &#39;args&#39;: {&#39;x&#39;: 3, &#39;y&#39;: 9}}, {&#39;type&#39;: &#39;addition&#39;, &#39;args&#39;: {&#39;x&#39;: 27, &#39;y&#39;: 45}}, {&#39;type&#39;: &#39;division&#39;, &#39;args&#39;: {&#39;x&#39;: 72, &#39;y&#39;: 6}}], &#39;step_no&#39;: 3, &#39;results&#39;: {&#39;multiplication_step_0&#39;: 27, &#39;addition_step_1&#39;: 72, &#39;division_step_2&#39;: 12.0}, &#39;final_response&#39;: &#39;3 multiplied by 9 is 27. Adding 27 to 45 gives 72. Finally, dividing 72 by 6 results in 12.0.&#39;, &#39;end&#39;: True}}<br>--------------------<br>4.006105899810791</pre><p>Thanks for your time. I hope this helped you develop an understanding of AI Agents in general and the usability of LangGraph for AI Agents.</p><p>If you enjoyed the article, I invite you to follow me for future content. Additionally, feel free to connect with me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>.</p><p>You might like my other related articles,</p><ul><li><a href="https://medium.com/@Shrishml/making-our-own-code-interpreter-part-1-making-of-a-sandbox-382da3339eaa">Making our own code interpreter: making of a sandbox</a></li><li><a href="https://medium.com/@Shrishml/emergence-6d3eb6a27cbb">Emergence</a></li><li><a href="https://medium.com/@Shrishml/breaking-the-gmemory-barrier-how-zero-revolutionizes-large-language-model-training-8e00d2e2f30a">Breaking the Memory Barrier: How ZeRO Revolutionizes Large Language Model Training</a></li><li><a href="https://medium.com/@Shrishml/lora-low-rank-adaptation-from-the-first-principle-7e1adec71541">LoRA: Low-Rank Adaptation from the first principle</a></li></ul><h4>Get more on it</h4><ul><li><a href="https://promptengineering.org/guiding-ai-conversations-through-dynamic-state-transitions/">Guiding AI Conversations through Dynamic State Transitions</a></li><li><a href="https://yoheinakajima.com/task-driven-autonomous-agent-utilizing-gpt-4-pinecone-and-langchain-for-diverse-applications/">Task-driven Autonomous Agent Utilizing GPT-4, Pinecone, and LangChain for Diverse Applications</a></li><li><a href="https://developer.nvidia.com/blog/building-your-first-llm-agent-application/">Building Your First LLM Agent Application | NVIDIA Technical Blog</a></li><li><a href="https://huyenchip.com/2024/03/14/ai-oss.html">What I learned from looking at 900 most popular open source AI tools</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0534345190dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-algorithmic-minds/a-primer-on-ai-agents-with-langgraph-understand-all-about-it-0534345190dc">A primer on AI Agents with LangGraph, understand all about it</a> was originally published in <a href="https://medium.com/the-algorithmic-minds">The Algorithmic Minds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to break into data science(2024)?]]></title>
            <link>https://medium.com/@Shrishml/how-to-break-into-data-science-2024-11f61352600e?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/11f61352600e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 08:52:04 GMT</pubDate>
            <atom:updated>2024-03-31T10:58:56.717Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3><strong>Is Data Science Right for You? A Beginner’s Guide to This Lucrative Field</strong></h3><p><em>Recently, I delivered a lecture on “Career in Data Analytics” for economics graduates at BASE, Bangalore. I thought this script could be valuable to a wider audience considering a career in data science. Cheers!</em></p><p>Hi everyone! I would like to start by introducing myself. I’ve been working as a data scientist for the past three years, gaining experience in both product and service-based companies. Before that, I was actually pursuing a Ph.D. in physics, specializing in astronomy. However, I decided to switch gears and pursue a career in data science. My background in physics has given me an edge in understanding and applying mathematical modeling, machine learning experimentation, and engineering systems. I firmly believe that people from diverse backgrounds can enrich the field of data science. Each person brings a unique perspective, and by working together as a community, we can all continue to learn and grow. That’s why I’m here today: to inspire you to consider data science as a potential career path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xD8fxcOtCn7XdwHXqGAOBw.png" /></figure><p>I know this session might seem intimidating to a lot of you. Actually, I felt the same way! Machine learning and data science seemed like some complex engineering that was way out of my league. I never even tried learning about them because I convinced myself it was just too technical. Until I had to learn it for one of my projects in astronomy. I realized that data science, at its core, is really about fitting models to data and that we have been doing for years.</p><p>Before we dive deeper, let us address the elephant in the room: is data science a brand new field? The answer is both yes and no. The massive availability of data thanks to the internet has undoubtedly revolutionized the way we analyze information. Businesses are scrambling to leverage these insights for a competitive edge. However, the core concepts behind data science have been around for centuries. Statisticians and econometricians, for instance, have been using similar methods for a long time. Think of econometrics as data science’s closest relative. They collect data, build models (like regression models), and use them to predict future trends, informing policy decisions. Similarly, during my PhD in astronomy, we dealt with massive datasets from satellites and telescopes, crafting models to understand the universe. So, while the scale and tools have changed dramatically, the fundamental principles of analyzing data to extract knowledge have a long and rich history.</p><p>Let’s break down data science into simpler terms. While it can be seen as a process where data goes in (X) and predictions come out (Y), like in regression analysis, there’s much more to it. We’ll delve deeper into the details later.</p><p>Data science sits at the intersection of three key areas: software engineering, business/domain knowledge, and statistics. Some jokingly describe a data scientist as someone with stronger statistics than a software engineer and better coding skills than a statistician — a jack of all trades, master of none. But this opens doors to specialization, which we’ll discuss later.</p><p>There’s no denying that data science has a strong engineering component. If you have an aversion to technology and engineering, it might be worth reassessing that. Coming from a non-engineering background myself, I can tell you it can be challenging initially. However, once you overcome that hurdle, things start to click.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcjgRJyw-Vc6sJyprDApBg.png" /></figure><p>I initially planned a slide on the perks of data science but realized what’s exciting for one person might not be for another. So, let’s explore what a typical data science job entails, and you can decide perks for yourself.</p><p>The first perk, for me at least, is the casual work environment. Suits never made sense to me, and here, casual attire is almost always the norm.</p><p>Data science thrives on variety. Each problem is unique, demanding different strategies, experiments, and solutions. It’s intellectually stimulating, kind of like a PhD program, but without the paper publishing stress. Reading papers, and blogs, and diving into codes are part and partials of the job, it never allowed me to miss my PhD days.</p><p>You’ll constantly be on the bleeding edge of technology, requiring continuous learning. Take a quarter off, and coming back can feel lost. The constant pressure to stay updated can be a source of anxiety for some and can be thrilling for some. But according to me for young graduates this is very helpful, they will overall learn how to learn, which will give them an edge in this changing job dynamics because of AI.</p><p>The good news is, that the data science community is incredibly supportive. You’ll feel at home and get almost instant help when you ask for it.</p><p>The data science industry is still young, and work structures haven’t fully solidified yet. This can lead to a situation where anyone working with data calls themselves a data scientist. Organizations might be unsure of the specific problem they need to solve, so the solution becomes: “Let’s hire a data scientist, they’ll figure it out.” While this lack of definition can be frustrating, it also creates a lot of opportunity.</p><p>A data science career can be a fantastic springboard for leadership positions. Similar to an MBA, it exposes you to a multitude of areas. You’ll need expertise in various domains, business operations, and technology. Working across multiple teams and with diverse stakeholders hones your communication and interpersonal skills as well. Actually, I would suggest you guys take this opportunity to become a full-fledged business executive.</p><p>The gender ratio in data science is skewed towards men. While this may not be a deciding factor for you, I wouldn’t mind seeing more women at work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZHoKVHwHDKoN0ZlUnONAA.png" /></figure><p>How data science impacts your daily life. From the movie recommendations on your streaming service to the products suggested on your shopping app, these are powered by recommender systems — data science models built by teams of data scientists, engineers, and domain experts.</p><p>The estimated arrival time of your Uber ride? That’s a machine learning model working behind the scenes, trained on massive datasets.</p><p>Even the personalized ads you see on YouTube and the credit card limit you receive — are all influenced by machine learning models.</p><p>And that’s not all! We’re seeing advancements like ChatGPT, a bot capable of human-like conversation. Self-driving cars, like those from Tesla, are another incredible example.</p><p>The point is, that machine learning and related technologies are woven into the fabric of our lives. If you choose data science, you might be working on projects that create these very applications.</p><p>Actually, I can say machine learning is almost everywhere now, In fact, your decisions, your emotions, and your life are being influenced by some or another model. Scary isn&#39;t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exvg1Kc419iO5SYu3JeIyA.png" /></figure><p>Some basic processes are almost followed everywhere. I will try to explain the process with an example.</p><p>Let us start with the problem of a bank. For instance, imagine a bank experiencing a rise in credit defaults. They have data on defaulters and non-defaulters, including features like age, income, salary, and location. Some data might be biased, while others might be objective. Here’s a question for everyone: holding all else constant, is gender a predictor of default risk? What do you think? Similarly, could a person’s state(or race) be a factor? Even if these variables are significant, should we include them in our model?</p><p>Now, when we have massive datasets from various sources, we need to merge, calibrate, and store them together. There will inevitably be missing data, or inaccuracies like people lying about their age or salary. This is where data cleaning comes in — a crucial step requiring significant effort to ensure high-quality data for modeling.</p><p>To recap, let’s think of a model as a black box<strong>.</strong> It takes inputs (X) like salary, gender, and age, and outputs (Y) the probability of someone defaulting on a loan.</p><p>After data cleaning, we need to select features that effectively predict default risk and comply with regulations. For instance, even if gender or race might be good predictors, they shouldn’t be included in the model due to ethical and legal reasons. Techniques like backward elimination, forward selection, and regression can help us choose the best features. Additionally, we can create new features by combining existing ones, like creating cross-products or polynomial features.</p><p>The exciting part: building the model! We split our data into three groups: training, validation, and testing. Different models are trained on the training data, and their accuracy and speed are evaluated on the validation set. The best-performing model based on latency and accuracy is chosen for deployment. We then measure its accuracy on the test data, hoping it performs similarly in real-world situations. Finally, the model is handed off to the engineering team for deployment. They create copies and the model starts making decisions, like how much credit you qualify for or whether you get a credit card.</p><p>Once deployed, we monitor its performance. As user behavior changes over time, we need to keep an eye on how well the model performs. If the accuracy drops significantly, it’s time to retrain the model with fresh data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SUaeI7FoAeM_KsT2kuOxw.png" /></figure><p>Now comes the juicy part: salary! Data science is currently one of the highest-paying jobs. As you can see, the salary range increases with years of experience, making it highly competitive compared to other industries. Return on investment is high, I learned it without paying any significant amount and earning somewhat similar to B-school. There is almost no entry barrier except your dedication. This is a good thing when you are entering but for insiders, this is not good. While many factors influence salary, but remember:</p><p>The efficient market hypothesis posits that asset prices reflect their true value based on available information.</p><p>You too will get your true value if you continue sharing information with the market. I will come back about this sharing information part of it on a few slides later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Nl5rb0FtP240OffTxvAIQ.png" /></figure><p>Let’s dive into the minimum requirements to join the data science bandwagon<strong>.</strong> First up, prioritize your LinkedIn profile. Building a network of over 3,000 data scientists unlocks hidden benefits. Your feed will be filled with relevant opportunities, learning materials, and suggestions. You’ll also gain insights into what’s trending in the market, allowing you to tailor your preparation. Remember, a strong, marketable LinkedIn profile is crucial for getting noticed by the right people. Consider taking a couple of online courses (YouTube offers many) to optimize your profile — these skills will be valuable regardless of your career path. You can tackle this daily alongside your other prep work. In fact, if you haven’t already, get started now!</p><p>With that groundwork laid, let’s move to the actual preparation. We’ll begin with Python basics, which can be mastered in a few weeks. Next, a solid understanding of libraries like pandas, NumPy, and Seaborn is essential. This might also take a couple of weeks. Practicing problems on platforms like HackerRank, LeetCode, and W3Schools is highly recommended.</p><p>Next comes basic machine learning<strong>.</strong> We’ll cover models like linear regression, logistic regression, decision trees, random forests, and other fundamental models. Here, the focus is on developing a basic understanding of how these algorithms work. Luckily, all these models are well-implemented in scikit-learn libraries, so you’ll primarily need to learn how to use them effectively. If time allows, you can also delve into the basics of deep learning at this stage.</p><p>A foundational understanding of statistics is assumed. This includes probability, descriptive statistics, parameter estimation, and basic inferential statistics like hypothesis testing. You don’t need to be an expert, but familiarity is helpful.</p><p>A little software engineering knowledge goes a long way<strong>.</strong> Grasping concepts like the model deployment lifecycle, cloud computing, Docker containers, and APIs will be beneficial during interviews. While hands-on experience isn’t essential, a basic understanding will definitely impress the interviewer.</p><p>Now you’re ready to tackle real-world problems through projects! Aim to build 3–4 projects and showcase them on your resume. This is your chance to get creative. Solve end-to-end problems, from data cleaning to deployment, and craft a compelling user story for each project. We’ll discuss building a strong project portfolio in more detail later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yK9RWNYgIyYsSORRXn6vA.png" /></figure><p>Data science, in my view, is like an art form — or perhaps a dark art, as some might say<strong>.</strong> It thrives on practice, just like Riyaz in music. Building strong daily habits early on is key to reaping the most benefits. The sooner you begin, the more intuition you’ll develop. Much like in other fields, a well-honed intuition is what separates experienced professionals from freshers — it allows you to approach problems creatively and efficiently.</p><p>Religious adherence to daily coding practice is essential<strong>.</strong> Start with honing your SQL and Python skills on platforms like HackerRank. Interview questions heavily rely on these areas, and gaining a solid foundation will put you ahead.</p><p>The more projects you tackle, the more you’ll solidify your learnings through real-world application. This reinforces your knowledge and showcases your abilities to potential employers. You don’t need to showcase every project — curate the best 3–4 for your portfolio, or select the most relevant ones for specific job applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWhtkVgqLwuh8_I_OiwG_A.png" /></figure><p>The project portfolio is undeniably the heart of your preparation<strong>.</strong> Many interview questions will revolve around your projects, and your resume might even get shortlisted based on the project keywords you include.</p><p>Remember, each project is a story, and we crave a captivating and complete story. Incompleteness can be just as off-putting. Strive for end-to-end projects that clearly explain the problem you’re addressing, the data you used, the data cleaning challenges you faced, the modeling techniques you employed, and finally, how you deployed the solution. Avoid overused projects like predicting California housing prices or character recognition — anything readily found on YouTube or the internet is likely boring.</p><p>By crafting a compelling narrative, you can subtly guide the interview toward your areas of expertise. This is an art form that gets honed with experience. Don’t shy away from interviews — everyone is a learning opportunity, so take advantage of them!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*moxvhU4BgHXFl1e6DfPZMQ.png" /></figure><p>If you want to take one thing from this session take this. Your resume is the key to getting your foot in the door. Recruiters only have a split second to glance at your resume, and Applicant Tracking Systems (ATS) using AI and keyword matching might discard it before a human ever sees it. This happens when there’s a flood of applications, making it impossible to review them all. An ATS-friendly resume is your best bet — it should be packed with relevant keywords and formatted for easy reading by the system. This significantly increases your chances of reaching the hiring manager’s desk.</p><p>So, once you’re past the initial hurdle, make a strong impression! Your resume should be a smooth sailing experience for the reader, with minimal cognitive load. Here are some key points:</p><ul><li><strong>Keep it to one page.</strong> No exceptions, no matter how much you want to showcase.</li><li><strong>Include hyperlinked references and contact information.</strong> Be prepared in case you make it to the interview stage.</li><li><strong>Space is precious!</strong> Treat your resume like real estate and use it efficiently.</li><li><strong>Craft a mini-story for each project.</strong> Follow a problem-solution-result template to showcase your approach and achievements.</li><li><strong>Invest time in building a stellar resume.</strong> Use online scoring tools, watch resume reviews, or resume roasts (you might even see these pop up on your LinkedIn feed if you build a strong network).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuJzT1ci7pZle4MQHYBsRQ.png" /></figure><p>We previously discussed the efficient market hypothesis, suggesting you’ll eventually reach your true value in the job market<strong>.</strong> However, this assumes all relevant information about you is readily available.</p><p>A strong digital presence bridges this gap<strong>.</strong> Regularly contributing to platforms like Medium, perhaps with 20 technical blogs, can significantly improve your discoverability. With a well-established online presence, potential employers may even find you instead of the other way around.</p><p>Networking goes beyond just connecting with people on LinkedIn to improve your feed<strong>.</strong> Building strong professional networks involves making genuine connections, fostering friendships, and potentially even collaborating on projects. These bonds can pay off significantly later in your career.</p><p>Many successful founders, like Asneer Grover and Sachin Bansal, met their co-founders in college or at top business schools. Invest time in getting to know your classmates and colleagues — you never know who might become a future co-founder. Enjoy.</p><p>If you liked the above you might like following</p><ul><li><a href="https://medium.com/@Shrishml/my-2-years-in-corporate-after-academia-an-opinionated-take-9b7ea1dfec7d">My 2 years in corporate after academia: an opinionated take</a></li><li><a href="https://medium.com/@Shrishml/how-exactly-to-make-career-choices-in-this-noisy-world-655df57336a4">How exactly to make career choices in this noisy world?</a></li></ul><p>I invite you to follow me for more insights. Additionally, feel free to connect with me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11f61352600e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How exactly to make career choices in this noisy world?]]></title>
            <link>https://medium.com/@Shrishml/how-exactly-to-make-career-choices-in-this-noisy-world-655df57336a4?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/655df57336a4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[careers]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 09:46:16 GMT</pubDate>
            <atom:updated>2024-02-23T05:53:04.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to make a career choice in this noisy world</h3><p>In our fast-moving world, it’s becoming tough to stick to one job (or one place) for our entire life, even if we really want to. There will be moments when we have to decide about our career (or other things). The choices we make during these times define our lives, just like Nemo in the movie Mr. Nobody.</p><p>Our life is a big rolling snowball of all the choices we make. It seems important to make careful and well-informed(mostly about ourselves) decisions. We need to be thoughtful, or we might risk leaving things to passion, given how fragile our sense of passion can be.</p><p>Hopefully, someday we will discover our true calling (if that’s a real thing), and once we reach that point, these small decisions won’t bother us much (as they say in the podcasts). But until then, having some mental tools for making decisions would be really helpful.</p><p>Let me share my own experience and a data-driven template to make career decisions. I’ve recommended this approach to many others, and it seems to work well. It’s also very adaptable. This simple template is embarrassingly easy and straightforward to make, but I’m not sure how easy it is to follow. Let us try this out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Acqt5i7ZFuSpZ8Gz" /><figcaption>Photo by <a href="https://unsplash.com/@bdchu614?utm_source=medium&amp;utm_medium=referral">Brendan Church</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Career Options</h3><p>Let me start by explaining the options I had.</p><p>I pursued a Master’s degree in Physics and conducted research in Astronomy. It was something I excelled at without much effort. From as far back as school, I was certain I’d become a physicist — there was no doubt about it. The plan was to become a professor, to teach physics at a university.</p><p>During my Ph.D. studies in Astronomy, I also delved into economics academically(solving problems from Nicholson’s microeconomics books). I found it quite enjoyable, and I realized that if I hadn’t pursued physics, economics could have been my alternative path. It’s a subject that combines intuition, reality, and mathematics much like physics does.</p><p>Out of curiosity and a bit of FOMO (Fear Of Missing Out), I also started learning machine learning. I found it fascinating and eventually decided to pursue it as a career, partly because of the rewards it offered, including financial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*bWLvCDS-9kqOaBZa4_LAOg.png" /><figcaption><a href="https://www.youtube.com/watch?v=5KT2D-L283k&amp;ab_channel=CokeStudioIndia">Look how immersed he is</a>.</figcaption></figure><p>Lastly, I’ve always had a love for music. I admired the artists of Coke Studio who could immerse themselves in their music and attain a state of flow effortlessly. Since I was a child, I’ve had a desire to learn music, and my closest friends happened to be musicians. I still hold a dream of pursuing music when I’m older and more financially stable. I’ve made multiple attempts to learn music, but unfortunately, I lack a natural instinct for it. A friend who’s a musician once explained that you feel the beat with your heart, not your brain. Despite my efforts, I’ve struggled to hear it as well as my classmates did in the various music classes I’ve tried. I still continue to work on it, hoping that one day I’ll suddenly start feeling it ( as my friends console me). Realistically, though, I understand that music won’t be my career path.<br>Now, the question is how I ultimately decided which pursuits to turn into a career and which ones to keep as hobbies.</p><h3>The Matrix</h3><p>We begin by creating a simple table with your various options listed as column names. For me, it was <strong>Music</strong>, <strong>Physics</strong>, <strong>Economics,</strong> and <strong>Data Science</strong>. You can consider adding more options. In the rows of this table, you input real-life factors such as:</p><p>1. <strong>Opportunities in the Field</strong>: How many chances there are for success in that area.<br>2. <strong>Personal Interest</strong>: How much do you enjoy engaging in that specific field?<br>3. <strong>Proficiency</strong>: How skilled you are at performing tasks related to that field to secure a job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*1JitgB3Uo_bjY6JkiJSgqA.png" /><figcaption>The matrix should look like this.</figcaption></figure><p>You’re free to include additional factors if they matter to you, such as the location you’d be working in. In my case, all cities hold the same value.</p><p>Following this, you assign scores to each of these factors for each option, typically on a scale of 1 to 10. For instance, in the “<strong>Opportunities in the field</strong> ” row for the <strong>Music </strong>column, I would rate myself a 2 out of 10 because I don’t see substantial career prospects there, statistically. In the “<strong>Personal Interest</strong>” row, I would score myself 9 out of 10 for <strong>Physics </strong>since I know I genuinely enjoy it. And so on.</p><p>Lastly, you sum up these scores vertically for each option. Applying this method, I find that <strong>Data Science (25) </strong>emerges as the clear winner for me. Despite not having as strong a liking or proficiency in it as I do in physics, the significant opportunities within the field make up for the difference in the overall total.</p><p>To add a touch of creativity, you can also assign <a href="https://edu.gcfglobal.org/en/excel-tips/use-sumproduct-to-calculate-weighted-averages/1/#">weights </a>to these rows. For example, as you progress in your career and become financially stable, you might want to give more importance to the “<strong>Personal Interest</strong>” factor.</p><h3>Knowing thyself</h3><p>Up to this point, the process appears straightforward. However, the numbers presented in this approach hold a certain complexity.</p><p>Each of these numbers I’ve placed in the table draws directly from my understanding of my own capabilities and inclinations. Assigning these numbers requires a significant amount of contemplation and self-awareness. Here lies a minor challenge — comprehending oneself is not always easy, and misjudgments about oneself are quite common. In addition, certain numbers I’ve entered stem from my perception of the broader world or the circumstances around me. It’s worth noting that this can also be influenced by specific situations. For instance, a child born to a renowned musician might rate their own opportunities at an 8 out of 10.</p><p>Nonetheless, despite these intricacies, you can always give this template a shot. It provides a structured way to assess and compare various paths based on both your self-knowledge and your understanding of the external environment.</p><h3>Estimating world</h3><p>The numerical values we place in the matrix require knowledge of the external world as well. In the process of decision-making, it becomes crucial to evaluate various options and their potential. According to Ray Dalio, the closer your world model is to reality, the greater the rewards you can expect to receive.</p><p>Being aware of external opportunities is essential when making choices. It’s little more than just staying up-to-date with the news; it involves understanding how the world functions. Analyzing trends acts as a safeguard against unrealistic expectations, aligning us with achievable outcomes. Staying attentive to shifts empowers us to choose actions that match emerging needs and circumstances.</p><p>To navigate this effectively, seeking insights from individuals with greater knowledge (wider view), like mentors, friends, or experienced advisors, proves invaluable. Their guidance refines our judgment, making our decisions more reliable.</p><p>I hope this has been helpful to you. If you enjoyed it, I invite you to follow me for more insights. Additionally, feel free to connect with me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=655df57336a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My 2 years in corporate after academia: an opinionated take]]></title>
            <link>https://medium.com/@Shrishml/my-2-years-in-corporate-after-academia-an-opinionated-take-9b7ea1dfec7d?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b7ea1dfec7d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[academia]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[phd]]></category>
            <category><![CDATA[phd-student]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 06:32:34 GMT</pubDate>
            <atom:updated>2023-07-16T06:32:34.428Z</atom:updated>
            <content:encoded><![CDATA[<p>It has been nearly two years since I bid farewell to academia and ventured into the captivating realm of a corporate career as a Data Scientist, the sexiest job of the 21st century as they say. But let’s rewind a bit. Back in the day, I was involved in my astronomy Ph.D. program at NISER in Bhubaneshwar. The field is incredibly exciting, and still attracting countless enthusiasts. Collaborating with an exceptional international team at IUCAA, Pune, under the guidance of my cool and supportive mentor. However, academia, as a system, left me with a mix of emotions, particularly concerning financial security and mental well-being.</p><p>Bidding farewell to academia felt akin to separating from a disloyal partner. The pleasures of teaching, research, and the indulgence of abundant time to contemplate were what I cherished. Fueled mainly by American science fiction, similar to those of Christopher Nolan, I fostered the aspiration of being a professor or scientist. These days, I just label science fiction as mere fiction. Partially in jest, I acknowledge my former naivety, accepting the fault as my own. It appears I embarked on this relationship with misguided anticipation.</p><p>Before that phase of my life, I completed my B.Sc. in Physics from Delhi University, fueled by an unwavering passion that led me to consider nothing but physics as a career since my school days. Physics came effortlessly to me, and clearing semester exams felt like a walk in the park. I never recall pulling all-nighters to cram for any exam, earning me the reputation of being a miracle among my classmates. At one point, I even contemplated teaching physics to JEE aspirants, but soon discovered that those institutions didn’t truly delve into the beauty of the subject. They focused more on problem-solving without savoring the true essence of physics. Nevertheless, I retain a strong grasp of physics concepts and happily assist students preparing for the JEE. As for data science, I’m still honing my command, clarity, and mental maps in this field, though I’m progressing rapidly.</p><p>Currently, I am venturing out on a limb by sharing my critical viewpoint, cognizant of the countless positive elements of academia (the reason why many of us gravitate towards it after all). It’s important to note that my commentary pertains specifically to Ph.D. programs in theoretical physics and other fundamental sciences. The scenario could be entirely different for those venturing into computer science, economics, or management. <br>My goal is to illuminate specific facets, enabling aspiring academics to make educated choices, and simultaneously sharing tales from my corporate voyage. I would advise taking my insights with a pinch of skepticism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YuhuZPzOEDlYtnHQ" /><figcaption>Photo by <a href="https://unsplash.com/es/@thelondoner?utm_source=medium&amp;utm_medium=referral">Tim Alex</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What is the END goal?</h4><p>One coveted outcome is to acquire the esteemed title of a tenured professor, complemented by inclusive health coverage for your whole family. Imagine a life with an abundance of time, working a 20-hour week officially (with occasional additional administrative duties), and enjoying the liberty to shape your own timetable. There’s also the appealing prospect of obtaining funds for the research that you are passionate about. It’s worth mentioning that in India, professors earn more than their American peers, and the job security they enjoy is almost akin to a government guarantee. Intriguingly, a few tenured professors seem to do very little work, choosing instead to savor life’s pleasures. However, one must acknowledge that the higher the position’s reward, the steeper the climb and the associated risks and opportunity costs, at least in my view. Yet, speaking candidly, I would willingly opt for such a life if there were no opportunity costs to consider.</p><p>However, it’s noteworthy that these circumstances are currently undergoing change. The once-relaxed nature of government jobs is shifting as they strive to boost efficiency — a trend likely to affect academia in the near future, following the precedent set by banks and other public sector undertakings.</p><p>In the corporate sphere, the apex goal often revolves around achieving financial freedom. This might entail building a substantial stock or cash portfolio, investing in property for rental income, or generating passive earnings. Some organizations also provide Employee Stock Ownership Plans (ESOPs), fostering a sense of ownership among employees and aligning their interests with the company’s. This could be a significant stride toward financial independence. As I say, financial freedom is the mother of all freedom.</p><h4>Job Prospect</h4><p>Now, let’s dissect the job market from the perspective of the basic principle: supply and demand. For example, in the software development field, there’s an abundance of qualified individuals and even more job vacancies available. On the flip side, the count of physics Ph.D. holders is comparably low, and thus, the requirement for their specialized knowledge is also less. However, it’s crucial to remember that during World War II, there was a massive spike in demand for physics specialists, for rather obvious reasons.</p><p>Landing a job in academia is notably tough and incurs a high opportunity cost, often requiring numerous postdoctoral roles and solid relationships within the academic circle. It’s not uncommon for researchers to undertake two or three postdocs, which help them acquire useful experience and extend their networks. Being able to publish in esteemed journals, showcase remarkable research prowess, and secure external funding are imperative. Guidance from esteemed advisors is crucial for opening doors and acquiring endorsements. While the path is strenuous, the satisfaction of adding to the body of knowledge and shaping the direction of one’s field makes it rewarding for those who are deeply passionate about academia.</p><p>Contrarily, getting a job in the corporate world is typically deemed less complex. Numerous corporate positions are viewed as less rigorous, offering ample preparation time and simpler prerequisites. Additionally, previous industry internships can considerably facilitate the transition into a corporate role. In the United States, it’s quite typical for around two-thirds of Ph.D. graduates to pursue careers in industry. While this tendency hasn’t gained substantial momentum in India yet, it’s optimistic to think that in the forthcoming years, more Ph.D. students will explore options in the corporate realm.</p><p>A number of elements contribute to this divergence. First off, the isolated academic sectors prevalent in India often concentrate on research areas that might not be in sync with market needs. This discordance creates a disconnect between academic education and corporate expectations, making the shift to business roles more daunting. Furthermore, the mindset of Ph.D. candidates also impacts the situation. It’s essential for candidates to start preparing for industrial roles right from the outset of their Ph.D. journey, which includes seeking pertinent internships and getting acquainted with practical industry procedures.</p><p>In order to bridge this divide, academia should actively promote and enable collaborations with industry. Encouraging internships, joint research endeavors, and industry-focused coursework can boost the practical abilities and industry relevance of Ph.D. programs. By nurturing a closer relationship between academia and industry, it becomes more achievable for Ph.D. candidates to explore a variety of career paths beyond academia.</p><h4>Work-life balance</h4><p>In the corporate arena, staying abreast of the latest developments is crucial, and ongoing skill enhancement is a must. You’ll find yourself continuously on your feet, adapting to emerging technologies, methodologies, and industry trends. Allocating a specific portion of time, about 2 hours daily, for upskilling activities becomes vital to remain competitive and significant in your field. After some time in the corporate world, where you’ve found your niche and are in a comfortable position, you could choose to strike a favorable work-life balance. However, this isn’t recommended — it’s more beneficial in the long run to learn to enjoy your work.</p><p>In contrast, academia provides a more balanced work-life scenario. Once you gain expertise in your specialized field and set a steady curriculum, the necessity for constant updates and skill improvement decreases. You can relish a sense of stability and devote more time to research, teaching, and other academic endeavors without the persistent pressure to continually augment your skills. This facilitates a better balance between work and personal life, offering the chance to delve deeper into your specific area of knowledge.</p><h4>Lack of skin in the game in the Indian academic system</h4><p>I once read a book titled “Skin in the Game” by Nicholas Taleb, which significantly influenced my decision to leave academia. The book taught me about risk, decision-making, and who reaps the benefits of those decisions. It delved into how your life can be altered by decisions made by others, to what extent you should allow that, and how you can build a system resilient to such influences or at least be aware of such situations in your surroundings.</p><p>The Indian academic system frequently suffers from a lack of accountability and personal commitment. While your academic guide might seem proficient, human behavior is an unavoidable factor.</p><p>The system’s power dynamics heavily tilt in favor of those in authoritative positions, such as your academic guide. Their influence over your five-year tenure is significant, while the repercussions of failure bear down more on you than on them. This unequal risk-reward scenario is not unusual.</p><p>In this setup, you’re left with minimal bargaining power, placing you at a disadvantage. As your Ph.D. journey progresses, your bargaining power further dwindles. You may notice a change in your guide’s behavior towards you from the first to the fifth year. Such inequalities might be bearable if your guide could secure you a permanent position, but unfortunately, this is an elusive outcome for most.</p><p>Contrarily, the corporate world presents a different dynamic where you hold more leverage and adaptability. After gaining some years of experience, you can look for other opportunities and switch roles or companies if necessary. Unlike academia, where the individual bears the brunt of the risk, in corporate settings, the responsibility is spread across the team. If a project fails, your manager shares a proportionate part of the blame.</p><p>Furthermore, the emphasis in corporate environments is on teamwork and shared objectives. Colleagues collaborate towards common goals, fostering a sense of unity. This cultivates a work atmosphere where everyone has a relatively equal stake in the game and is motivated by a collective purpose.</p><h4>Is there unemployment outside?</h4><p>Actually, it seems the situation is the reverse. Job opportunities are increasing, even amidst high-interest rates. The US Federal Reserve is struggling to elevate the unemployment rate to alleviate inflation (read more about the Phillips curve to understand this concept).</p><p>Many of my academic peers express concern about job scarcity in the market. However, my experience tells a different story. There is a significant demand for Ph.D. or science graduates in fields like data science. Other potential areas to explore include digital marketing and quantitative finance, but preparing for these fields necessitates serious commitment. I once read a book titled “How I Became a Quant: Insights from 25 of Wall Street’s Elite,” where most contributors had a physics background and shared their experiences transitioning from academia to the corporate world. It’s a worthy read if you’re already contemplating this shift (and I presume you are since you’re reading this article).</p><p>In India, digital marketing is a burgeoning field, presenting a vast array of opportunities. While the process might be more chaotic compared to a job in academia, it also offers substantial financial rewards. The field of management is always vibrant and continually seeks a diverse range of talents.</p><p>I believe that industries are in dire need of individuals with a research backgrounds. The default stance in business meetings doesn’t always align with causality. Research methodologies and measurement processes can be extremely beneficial in these contexts. However, it’s important to note that it’s up to academics to demonstrate this value, not the other way around.</p><h4>Money matters</h4><p>Now, let’s talk about salary. In academia, a typical Ph.D. candidate may earn around 40,000 INR per month over a 5-year period. In contrast, in the corporate world, five years of work experience can catapult you into a much more financially secure position. With the growth of the service sector in India, the rise of remote work, and opportunities to freelance (often paid in dollars), Indian white-collar workers enjoy a competitive edge. The advantage of earning in a strong currency like the dollar while spending in rupees cannot be understated.</p><p>Admittedly, a professor’s salary can be quite generous. However, with the same years of experience, a corporate worker’s earning potential is often far higher. This isn’t a puzzling fact, so I won’t dwell on it further. However, it is worth noting that in academia, salary growth tends to hit a ceiling eventually.</p><p>Being a part of the corporate world means to thrive, it’s necessary to position yourself within the top 10% of the workforce. Failing to do so can diminish your leverage, as employers are continually balancing their books and managing the bottom line. The corporate world operates with the fundamental objective of maximizing shareholder value, at times, without much regard for individual employees. However, your perspective can change if you have a stake in the company, such as through employee stock ownership plans (ESOPs) or as a founder.</p><p>In the realm of financial stability, you might find a significant shift in your perspective. If you’ve consistently felt the weight of financial insecurity, or perhaps developed a negative attitude towards the wealthy, these sentiments tend to evaporate once you have acquired some wealth of your own.</p><h4>ssshhh! Mental health</h4><p>The significance of mental health is increasingly being recognized, especially in academia. My own patience with the system was deeply shaken when I had to face the tragic suicides of two senior Ph.D. students from my physics department, who were ironically both working on string theory and were close to me. This terrible experience left me in a state of shock for months. Although it might not be popular to mention this, I feel it’s my responsibility to highlight the urgent need for greater awareness.</p><p>Having financial security offers various benefits, extending beyond your lifestyle to positively influence your mental health. With a substantial income, you can afford the best support, like therapy from top-rated psychologists. You can also invest in personal fitness by hiring an excellent trainer or joining a sports club. Financial stability tends to enhance your relationships, marriage, and family life and allows you to surround yourself with positive, upbeat individuals. Therefore, a job’s impact is far-reaching, influencing not just financial security, but also shaping your lifestyle, relationships, and mental health.</p><p>In the corporate sphere, the allocation of responsibilities often results in some degree of detachment from your work. Interestingly, this detachment can lead to increased honesty, productivity, and sometimes a more critical assessment of your role. Regardless of whether you succeed or fail in your daily tasks, you continue to earn and gain valuable experience. Your errors become learning opportunities, adding to your value as an employee. The immediacy of the impact of your work is also very rewarding.</p><p>Finally, adopting a more realistic viewpoint has significantly improved my mental health. An insightful quote by renowned investor Ray Dalio reads, “The more your mental model of the world aligns with reality, the more rewards you can reap.” This sentiment is particularly true in the corporate world, where direct feedback and interactions with reality often take precedence over the idealistic perspectives found in academia. Such an environment fosters pragmatism, and acceptance of difficult realities, and occasionally even equips you with the power to instigate change.</p><h4>Do you enjoy your job?</h4><p>The general assumption is that Ph.D. students are fueled by an intense passion for their work and a profound fascination with their area of study. I too began my journey with the same level of enthusiasm, only to eventually understand that this could be a potential trap. Over the long haul, even the most intense passion can fade.<br>Previously, I didn’t discuss this issue much. In my experience, job satisfaction doesn’t come so much from the job’s nature, but rather from the story, we associate with it. This narrative is often shaped by our mental model of the world and the conditioning we have been through. Even in academia, you’ll find a fair share of so-called boring tasks such as writing papers or handling administrative duties. I’ve seen numerous professors whose work primarily revolves around admin tasks.<br>Corporate work too has its mix of interesting, necessary, and at times monotonous tasks. You might even find it leaning more toward the necessary ones. But the sense of meaning is often derived from a narrative that we ourselves construct or one that is fostered by the company.</p><h4>At last corporate politics</h4><p>Wherever money flows, economics follows; and wherever power exists, politics is inevitable. It’s best to embrace this reality, much like we often find ourselves engrossed in political discussions during our Ph.D. studies.</p><p>During my Ph.D., I found myself discussing politics and history more than focusing on my work. In truth, you can’t avoid this dynamic, so it’s beneficial to learn to navigate it. I can assure you, it can even become enjoyable if you don’t take things too personally.</p><p>Yes, politics exist in the corporate world too, but compared to academia, the stakes are often higher, and the rewards can be larger — particularly in a burgeoning economy like India’s.</p><p>If all of this information has left you feeling more uncertain than before, don’t worry. I encourage you to reach out to me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>. I have guided several people through the transition from academia to the corporate world and I would be more than happy to assist you as well. Whether you need help understanding specific aspects of the corporate environment or you’re simply looking for advice on how to make the transition smoother, feel free to contact me. I’ll do my best to provide the guidance and support you need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b7ea1dfec7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LoRA: Low-Rank Adaptation from the first principle]]></title>
            <link>https://medium.com/the-algorithmic-minds/lora-low-rank-adaptation-from-the-first-principle-7e1adec71541?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e1adec71541</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[deeplearing]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 05:52:52 GMT</pubDate>
            <atom:updated>2024-09-08T09:45:08.567Z</atom:updated>
            <content:encoded><![CDATA[<p>At the heart of all deep learning models lies a sequence of matrix multiplications, interspersed with the introduction of non-linear functions such as Sigmoid, ReLU, and GeLU. The recent surge in large language models (LLMs) has confirmed their exceptional potential in a variety of applications. However, the practical deployment and fine-tuning of these massive LLMs present significant cost and efficiency challenges for data science teams.</p><p>The pace of advancement in this field is staggering, with a steady stream of new research papers and software packages being released. These resources are designed to minimize the cost and duration of training and inferring with LLMs. Considering this rapid progression, it wouldn’t be surprising to see LLMs running on our handheld devices in the near future.</p><p>In today’s discussion, I’ll be exploring a groundbreaking paper on Low-Rank Adaptation (LoRA). This research proposes a solution to the cost and efficiency challenges posed by LLMs by freezing the pre-trained model weights and injecting trainable rank decomposition matrices into each layer of the Transformer architecture. This innovative approach dramatically reduces the number of trainable parameters for downstream tasks, resulting in significantly reduced GPU memory requirements and improved training throughput.</p><p>By harnessing the power of linear algebra, LoRA provides a more feasible solution for fine-tuning LLMs, without any additional inference latency or compromise on model quality. The paper even presents empirical evidence on the efficacy of LoRA, paving the way for a more streamlined approach to LLM adaptation.</p><p>We’ll delve deeper into the details of this paper, aiming to illuminate the foundational concepts behind LoRA and understand its impact and potential applications. Our exploration will also include a discussion on the newly released tools and packages that facilitate the integration of LoRA with PyTorch models. These resources provide invaluable support to data scientists seeking to leverage the advantages of LoRA in their work with RoBERTa, DeBERTa, and GPT-2 models, among others.</p><p>Join me as we navigate through the intricate landscape of large language models and explore how LoRA is redefining the way we approach model fine-tuning and deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NhQsYHa630mNgrHQ" /><figcaption>Photo by <a href="https://unsplash.com/@brenomachado?utm_source=medium&amp;utm_medium=referral">Breno Machado</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is the rank of the matrix?</h3><p>The rank of a matrix is a fundamental concept in linear algebra. It is defined as the maximum number of linearly independent columns (or equivalently, rows) in the matrix. In other words, it tells us the maximum number of dimensions spanned by the vectors represented by the matrix. A crude definition can be the amount of information contained in the matrix.</p><p>If the rank of a matrix is equal to its smallest dimension (either the number of rows or columns), the matrix is said to have &quot;full rank&quot;. A matrix that does not have full rank is said to be rank deficient.</p><p>Here&#39;s a simple example:</p><p>Consider a 3x3 matrix A:</p><pre>A = [[1, 2, 3],<br>     [2, 4, 6],<br>     [3, 6, 9]]</pre><p>You can see that each row in this matrix is a multiple of the others, and therefore they are all linearly dependent. In this case, the rank of the matrix is 1, because only one row is linearly independent.</p><p>Let&#39;s take another example:</p><pre>B = [[1, 2, 3],<br>     [4, 0, 6],<br>     [7, 8, 9]]</pre><p>In this matrix, you can see that no row is a multiple of another, which means all rows are linearly independent. So, the rank of matrix B is 3, as there are 3 linearly independent rows (or columns).</p><p>To calculate the rank of a matrix in Python, you can use the numpy.linalg.matrix_rank() function. For example:</p><pre>import numpy as np<br><br>A = np.array([[1, 2, 3], [2, 4, 6], [3, 6, 9]])<br>print(&quot;Rank of A:&quot;, np.linalg.matrix_rank(A))<br><br>B = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])<br>print(&quot;Rank of B:&quot;, np.linalg.matrix_rank(B))</pre><pre>Rank of A: 1<br>Rank of B: 2</pre><p>This script will print out &quot;Rank of A: 1&quot; and &quot;Rank of B: 2&quot; respectively. <em>Note that in the second case, even though there are no rows or columns that are exact multiples of others, the matrix is still rank-deficient because one row can be represented as a linear combination of the other two. This demonstrates how the rank can be less than the number of rows or columns.</em></p><h3>Low-rank approximation of matrix</h3><p>A matrix A of rank r can be factored uniquely into two separate matrices. This is represented as A = CR. Here, A is an m x n matrix, C is an m x r matrix whose rank is also r, and R is an r x n matrix, also with rank r.</p><p>Essentially, the rank of a matrix is the smallest value of r that allows the equation A(nxn) = C(nxr) R(rxn) to hold true. It’s important to note that if r is smaller than the actual rank of the matrix, it’s still possible to find an approximate solution to the equation A(nxn) = C(nxr) R(rxn).</p><p>The Rank Factorization Theorem allows us to represent a matrix A as a product of two matrices, capturing the essential structure of A in a potentially more compact and numerically stable manner. It is particularly useful when A is of high rank but can be well-approximated by a matrix of lower rank, which is often the case in applications such as image processing and machine learning.</p><p>Let’s put this into practice with an example and Python code:</p><p>Consider a 5x5 matrix A:</p><pre>A = np.array([[19,  9, 12, 19,  8],<br>              [ 0,  0,  0,  0,  0],<br>              [ 3,  1,  0,  3,  0],<br>              [ 6,  2,  0,  6,  0],<br>              [25, 11, 12, 25,  8]])</pre><pre>import numpy as np<br><br><br>A = np.array([[19,  9, 12, 19,  8],<br>              [ 0,  0,  0,  0,  0],<br>              [ 3,  1,  0,  3,  0],<br>              [ 6,  2,  0,  6,  0],<br>              [25, 11, 12, 25,  8]])<br><br>print(&quot;Rank of A:&quot;, np.linalg.matrix_rank(A))<br><br>Output:<br> Rank of A: 2</pre><p>Let us say we find out some C(5x2) and R(2x5) that satisfy A=CR. (can be found using a technique called singular value decomposition: SVD).</p><pre>C = np.array([[4, 1],<br>              [0, 0],<br>              [0, 1],<br>              [0, 2],<br>              [4, 3]])<br><br>R = np.array([[4, 2, 3, 4, 2],<br>              [3, 1, 0, 3, 0]])<br><br>print(&quot; CR is :&quot;, C@R)<br><br>Output:<br> CR is : [ [19  9 12 19  8]<br>           [ 0  0  0  0  0]<br>           [ 3  1  0  3  0]<br>           [ 6  2  0  6  0]<br>           [25 11 12 25  8]]</pre><h4>LORa for a linear regression model</h4><p>Let us try the same trick to compress a simple linear model(y= Wx+b),</p><pre>import torch<br>import numpy as np<br>torch.manual_seed(0)<br><br># Dimensions<br>n, m = 10, 10  # n: input dimension, m: output dimension<br><br>#------------------------<br># ignore this part of code I just made it make a rank deficient matrix<br># it is highly probable that the W matrix will be a rank 2 through this process<br>nr,mr= 10, 2<br>W = torch.randn(nr,mr)@torch.randn(mr,nr)<br># ----------------------<br>print(&quot;See how W looks like:\n&quot;,W)<br>b = torch.randn(n)<br><br><br>r= np.linalg.matrix_rank(W)<br>print(&quot;Rank of W:&quot;, r)<br># Random input x<br>x = torch.randn(n)<br><br># Compute y = Wx + b<br>y = W@ x + b<br><br>#--------------------------------<br># this is just to exact rank factorization, it can be ignored sfely<br><br># Perform SVD on W #<br>U, S, V = torch.svd(W)<br><br># For rank-r factorization, keep only the first r singular values (and corresponding columns of U and V)<br>U_r = U[:, :r]<br>S_r = torch.diag(S[:r])<br>V_r = V[:, :r].t()  # Transpose V_r to get the right dimensions<br><br># Compute C = U_r * S_r and R = V_r<br>C = U_r@S_r<br>R = V_r<br># -------------------------------------------<br><br><br># Compute y&#39; = CRx + b<br>y_prime = (C@R)@x+ b<br><br>print(&quot;Original y using W:\n&quot;, y)<br><br>print(&quot;y&#39; computed using CR:\n&quot;, y_prime)<br><br><br>print(&quot;Total parameters of W:\n&quot;, W.shape[0]* W.shape[1])<br><br>print(&quot;Total parameters of C and R :\n&quot;, C.shape[0]* C.shape[1] + R.shape[0]* R.shape[1])</pre><pre>Output: <br>See how W looks like:<br><br> tensor([[-1.0797,  0.5545,  0.8058, -0.7140, -0.1518,  1.0773,  2.3690,  0.8486,<br>         -1.1825, -3.2632],<br>        [-0.3303,  0.2283,  0.4145, -0.1924, -0.0215,  0.3276,  0.7926,  0.2233,<br>         -0.3422, -0.9614],<br>        [-0.5256,  0.9864,  2.4447, -0.0290,  0.2305,  0.5000,  1.9831, -0.0311,<br>         -0.3369, -1.1376],<br>        [ 0.7900, -1.1336, -2.6746,  0.1988, -0.1982, -0.7634, -2.5763, -0.1696,<br>          0.6227,  1.9294],<br>        [ 0.1258,  0.1458,  0.5090,  0.1768,  0.1071, -0.1327, -0.0323, -0.2294,<br>          0.2079,  0.5128],<br>        [ 0.7697,  0.0050,  0.5725,  0.6870,  0.2783, -0.7818, -1.2253, -0.8533,<br>          0.9765,  2.5786],<br>        [ 1.4157, -0.7814, -1.2121,  0.9120,  0.1760, -1.4108, -3.1692, -1.0791,<br>          1.5325,  4.2447],<br>        [-0.0119,  0.6050,  1.7245,  0.2584,  0.2528, -0.0086,  0.7198, -0.3620,<br>          0.1865,  0.3410],<br>        [ 1.0485, -0.6394, -1.0715,  0.6485,  0.1046, -1.0427, -2.4174, -0.7615,<br>          1.1147,  3.1054],<br>        [ 0.9088,  0.1936,  1.2136,  0.8946,  0.4084, -0.9295, -1.2294, -1.1239,<br>          1.2155,  3.1628]])<br><br>Rank of W: 2<br><br>Original y using W:<br> tensor([ 1.6207,  2.1148,  2.3849, -2.3917, -1.2117, -4.9171, -3.9770,  0.5812,<br>        -3.2889, -2.9090])<br><br>y&#39; computed using CR:<br> tensor([ 1.6207,  2.1148,  2.3849, -2.3917, -1.2117, -4.9171, -3.9770,  0.5812,<br>        -3.2889, -2.9090])<br><br>Total parameters of W:<br> 100<br><br>Total parameters of C and R :<br> 40</pre><p>This example clearly demonstrates that we can achieve identical results using two different models: one with 100 parameters and another with just 40. This is achieved by approximating the weight matrix. In fact, even if we set ‘r’ to a value less than the actual rank of the weight matrix, we can still obtain an acceptably approximated output.</p><p>When training a model like this, if we were to train the weight matrix ‘W’ using specific training examples and a loss function, it would be considerably easier and quicker to train matrices ‘C’ and ‘R’ instead. We employ a similar logic when training a language model (LLM) or in fact, any other big models, allowing for cost-effective training.</p><h3>LORa in LLMs</h3><p>Some extensive deep-learning models have demonstrated that their weight matrix often resides within low-rank spaces. For example, weight matrices of 1000x1000 dimensions have been observed to exist in spaces as low as rank 10. Former results in a total of 10⁶ trainable parameters while the latter results in just 20000 trainable parameters.</p><p>For more clarity, let’s consider training a Language Model (LLM). Suppose we have embedding vectors of 1000 dimensions. This would yield K, Q, and V matrices of 1000x1000 dimensions, each producing 10⁶ trainable parameters.</p><p><em>If this seems complex, simply remember that LLMs involve a series of matrix multiplications, and we aim to compress these matrices to a lower rank to reduce the number of parameters that need to be trained.</em></p><p>The fine-tuning process in this context is understood as a shift in all the W to W’ matrices within the model. We opt to keep W frozen, to avoid disrupting the stability of the base model. Instead, we introduce a change dW and decompose it into two low-rank matrices, A and B (dW = AB). The followings are estimates of trainable parameters if we choose r to be 8,</p><pre><br>W&#39;(1000x1000) =  W(1000x1000)+ dW(1000x1000)<br>dW(1000x1000) = A(1000x8) B(8x1000)<br>1000000 trainable params =&gt; 16000 trainable prameters</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*Q_ygJFnJaI3AS1n-zXQvdg.png" /><figcaption>Our reparametrization. We only train A and B. For above example r=8 and d =1000.</figcaption></figure><p>In practice, we don’t have to train all the matrices involved in a Language Model (LLM). We can still achieve competitive performance by just training a few target modules(Just Q, K, V, or any pairs of them) and keeping the rest frozen. Importantly, in LoRA (Low-Rank Adaptation) training, we’re not aiming to find the exact rank of the matrix and then perform rank factorization. Instead, we’re perfectly content with a preassumed value of ‘r’ (a hyperparameter) to attain an approximate solution.</p><p>The algorithm, therefore, is straightforward:</p><blockquote>1. Freeze the base model (W).<br>2. Approximate the change in W (dW) as the product of two matrices A and B, where ‘r’ is preassumed for some modules.<br>3. Train the adapter (the product of A and B) with the base model.<br>4. Incorporate the trained adapter into the base model (W’ = W + AB) and proceed with inference.</blockquote><h3>Performances</h3><p>According to the paper, we do not lose any accuracy from training in LoRA. In fact, in fact, we are gaining it even though we reduced the number of trainable parameters to less than 1 percent of the original.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*MGCMUXQEZX0-l1Pd0JrqrQ.png" /><figcaption>Performance of different adaptation methods on GPT-3 175B. We report the logical form validation accuracy on WikiSQL, validation accuracy on MultiNLI-matched, and Rouge-1/2/L on SAMSum. LoRA performs better than prior approaches, including full fine-tuning.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*fYAXlGw6YTJbW3a99dXOwQ.png" /><figcaption>Validation accuracy on WikiSQL and MultiNLI with different rank r. To our surprise, a rank as small as one suffices for adapting both Wq and Wv on these datasets while training Wq alone needs a larger r.</figcaption></figure><h3>Code implementations</h3><p>Code as simple as the following can implement the above algorithm using peft library. The full version can be accessed <a href="https://github.com/bigcode-project/starcoder/blob/main/finetune/finetune.py">here</a>.</p><pre>from peft import PeftModel<br>from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training, set_peft_model_state_dict<br><br><br>model = AutoModelForCausalLM.from_pretrained(<br>        &quot;bigcode/starcoder&quot;,<br>        use_auth_token=True,<br>        device_map={&quot;&quot;: Accelerator().process_index},<br>    )<br><br><br># lora hyperparameters<br>lora_config = LoraConfig(r=8,target_modules = [&quot;c_proj&quot;, &quot;c_attn&quot;, &quot;q_attn&quot;])<br><br><br>model = get_peft_model(model, lora_config)<br>training_args = TrainingArguments(<br>    ...<br>)<br><br>trainer = Trainer(model=model, args=training_args, <br>                  train_dataset=train_data, eval_dataset=val_data)<br><br>print(&quot;Training...&quot;)<br>trainer.train()<br><br># plugging the adapter into basemodel back<br>model = PeftModel.from_pretrained(&quot;bigcode/starcoder&quot;, peft_model_path)</pre><p>Thank you for taking the time to read my writing. If you enjoyed it, I invite you to follow me for future content. Additionally, feel free to connect with me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>.</p><p>You might like my other related articles,</p><ul><li><a href="https://medium.com/@Shrishml/making-our-own-code-interpreter-part-1-making-of-a-sandbox-382da3339eaa">Making our own code interpreter: making of a sandbox</a></li><li><a href="https://medium.com/@Shrishml/emergence-6d3eb6a27cbb">Emergence</a></li><li><a href="https://medium.com/@Shrishml/breaking-the-gmemory-barrier-how-zero-revolutionizes-large-language-model-training-8e00d2e2f30a">Breaking the Memory Barrier: How ZeRO Revolutionizes Large Language Model Training</a></li><li><a href="https://medium.com/@Shrishml/a-primer-on-ai-agents-with-langgraph-understand-all-about-it-0534345190dc">A primer on AI Agents with LangGraph, understand all about it</a></li></ul><h3>References</h3><ul><li><a href="https://arxiv.org/abs/2012.13255">Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning</a></li><li><a href="https://arxiv.org/abs/2106.09685">LoRA: Low-Rank Adaptation of Large Language Models</a></li><li><a href="https://arxiv.org/abs/2012.13255">Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning</a></li><li><a href="https://github.com/bigcode-project/starcoder/blob/main/finetune/finetune.py">starcoder/finetune/finetune.py at main · bigcode-project/starcoder</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e1adec71541" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-algorithmic-minds/lora-low-rank-adaptation-from-the-first-principle-7e1adec71541">LoRA: Low-Rank Adaptation from the first principle</a> was originally published in <a href="https://medium.com/the-algorithmic-minds">The Algorithmic Minds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking the Memory Barrier: How ZeRO Revolutionizes Large Language Model Training]]></title>
            <link>https://medium.com/the-algorithmic-minds/breaking-the-gmemory-barrier-how-zero-revolutionizes-large-language-model-training-8e00d2e2f30a?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e00d2e2f30a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[deepspeed]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Sun, 21 May 2023 15:28:15 GMT</pubDate>
            <atom:updated>2024-02-08T12:06:13.369Z</atom:updated>
            <content:encoded><![CDATA[<h3>Breaking the memory barrier: how ZeRO revolutionizes large model training</h3><p>Training powerful language models like GPT-3, one of ChatGPT’s precursors, is a resource-intensive affair. Estimates suggest that the cost of training GPT-3 from scratch could range between $4.6 m and $12 m. Much of this cost can be attributed to the heavy use of GPU machines, which is indispensable in training neural network-based models.</p><p>The computational demand for GPUs is well-known and has spurred researchers to devise innovative strategies to optimize both time and computational power, particularly for large language models (LLMs) and other hefty models. In the ongoing quest for cost-effective training methods, numerous papers and techniques have emerged, offering more economic training.</p><p>One significant method I’ve discussed previously is <a href="https://medium.com/@Shrishml/mixed-precision-training-all-a-data-scientist-needs-to-know-2660641c48d8">mixed precision training</a>. This technique serves as a primer in the context of large-scale model training. However, I’ll ensure that the concepts covered here are self-contained.</p><p>Today, our spotlight is on the <a href="https://arxiv.org/abs/1910.02054">ZeRO</a> paper by Microsoft Research. This seminal work has remarkably accelerated both the training and inference of LLMs in settings involving multiple GPUs or nodes.</p><p>Accompanying this breakthrough is the <a href="https://www.deepspeed.ai/training/">deepspeed</a> library, an invaluable tool conceived by the same Microsoft research team. Garnering over 25k stars on GitHub, this library, written with CUDA, C++, and Python, has revolutionized how we engage with large models. Its impact on simplifying and optimizing my work can hardly be overstated.</p><p>In the discussion that follows, I aim to unpack the fundamental principles outlined in the original ZeRo paper, giving you a peek into the mechanics underpinning this remarkable innovation.</p><h4>GPU memory calculation for loading an LLM</h4><p><strong>Memory required for inference</strong></p><p>To begin with, let’s address a fundamental question: How much GPU memory does one need to infer from a large language model?</p><p>Neural networks, regardless of their complexity, fundamentally boil down to a series of matrix multiplications. This is true for every neural network, including large models like the Dolly 3b. The model’s parameters, which are essentially the weights and biases, are stored as tensor objects.</p><p>If we were to load the Dolly 3b model onto a GPU, and each parameter was held in 32-bit floating point memory, how much memory would we need? Here’s the math: 32 bits equals 4 bytes, and with 3 billion parameters (noting that ‘b’ in 3b stands for billion or 10⁹), we’d require 4 bytes x 3 billion or 12 GB. That’s just to load the model.</p><p>On top of this, we’d need some additional memory for the computations — let’s assume about 2 GB.</p><p>So in essence, to load and run a model comprising 3 billion parameters, you’d need around 14 GB of GPU memory.</p><p><strong>Memory required for training</strong></p><p>Training a large language model (LLM), like ChatGPT, is different from merely loading it for inference. It requires more memory during runtime because we need to account for gradients, activations, and the states of the optimizer, alongside the original model parameters.</p><p>To simplify this, we’ll denote all the parameters in the LLM as ‘W’, and their associated gradients as ‘dW’. In any model, the size of ‘W’ and ‘dW’ would be identical.</p><p>Before we delve deeper, it’s crucial to familiarize ourselves with two key concepts — mixed precision training and the Adam optimization method.</p><p><strong>Mixed precision training</strong> is a technique where we store parameters and activations as 16-bit floating-point numbers (fp16). An fp16 number takes up 2 bytes of memory. For a model with 3 billion parameters, this amounts to 6GB (2 bytes * 3B). This method improves computational efficiency during both forward and backward propagation.</p><p>However, when it’s time to apply updates after the backward propagation, the mixed-precision optimizer maintains a 32-bit floating-point (fp32) copy of the parameters and all other optimizer states. This is because the calculations for the updates are more accurate in 32-bit.</p><p>Instead of directly updating the gradients like in stochastic gradient descent(updates of very stochastic and jumpy here), the <strong>Adam optimizer</strong> utilizes exponential moving averages of gradients to stabilize the updates. It maintains two estimates, ‘m’ and ‘v’, which are updated using decay rates ‘b1’ and ‘b2’. These estimates are bias-corrected and employed for weight updates. The <strong>Adam optimizer</strong> is known for its considerable fast convergence.</p><p>Using the <strong>Adam optimizer</strong>, we’ll have an fp32 copy of ‘W’ (4 bytes * 3B, amounting to 12GB), and an fp32 copy of both the moving average and variance of ‘dW’ (2 * 4 bytes * 3B, amounting to 24GB).</p><p>Although the Stochastic Gradient Descent (SGD) optimizer could be a simpler choice to reduce the memory occupied by the optimizer state, it doesn’t maintain the moving variance of the gradient. This would considerably slow down the training process, so it’s usually not an option.</p><p>Now, let’s break down the memory requirements:</p><blockquote>Parameters:<br>- fp16 Parameters: 2 bytes * 3B = 6GB</blockquote><blockquote>Gradients:<br>- fp16 Gradients: 2 bytes * 3B = 6GB</blockquote><blockquote>Activations:<br>- Memory required depends on batch size and context length</blockquote><blockquote>Optimizer States:<br>- fp32 Parameters: 4 bytes * 3B = 12GB <br>- fp32 Gradients (mean): 4 bytes * 3B = 12GB <br>- fp32 Gradients (variance): 4 bytes * 3B = 12GB</blockquote><blockquote>Total memory required = 6GB (fp16 Parameters) + 6GB (fp16 Gradients) + 12GB (fp32 Parameters) + 12GB (fp32 Gradients mean) + 12GB (fp32 Gradients variance) = 48GB</blockquote><p>We also need to allocate some extra working memory.</p><p>Hence, to start training an LLM with 3 billion parameters, we’ll need at least 48GB of GPU memory. A simple rule of thumb to remember is that memory required is about 16 times the number of parameters.</p><h4>Parallel Training</h4><p>In response to the high memory demands of training large language models, it might seem intuitive to integrate multiple GPUs into the process. However, distributed training involves more complexity than one might initially perceive. There are two fundamental components to manage: computation and communication.</p><p>Computation refers to the execution of training operations, such as the forward and backward passes and the updating of model parameters. On the other hand, communication involves the exchange of information between GPUs, such as gradients and model parameters.</p><p>The challenge here is to find an equilibrium that optimizes the compute-to-communication ratio. This means that we want to maximize the computational capability of the GPUs while minimizing the amount of communication between them. Too much communication could bottleneck the training process, slowing down the overall computational speed. Therefore, it’s essential to develop strategies that optimize this delicate balance.</p><h4>ZeRo-DP: Data Parallel training</h4><p>Parallel training may initially seem straightforward — just engage multiple GPUs (each exceeding 48GB memory), load the model onto every GPU, and distribute the data batches among them. Following a specific period, a combined operation known as ‘all gather’ is employed to accumulate gradient updates from all GPUs. However, this approach demands a whopping total of approximately 200GB GPU memory, an extravagant requirement.</p><p>This technique is not just expensive; it’s also inefficient. It fosters significant memory redundancy, primarily because it keeps replicas of the entire model on each GPU. This is an avoidable overhead as every GPU doesn’t need to hold a complete model copy, leading to inefficient resource usage. We must devise smarter strategies to maximize GPU potential and minimize wastage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlAuDP1E70FsldhBRsaALw.png" /><figcaption>The baseline version of data parallelism, we loaded the model into all available GPUs and partitioned data into batches to different GPUs. We observe that the most memory is being taken by optimizer states.</figcaption></figure><h4>Optimizer State Partitioning</h4><p>When training large language models, we observe that optimizer states are the primary memory hoggers. An immediate strategy for optimization is to distribute, or ‘partition’, these optimizer states across multiple GPUs.</p><p>In this setup, each GPU runs the complete forward and backward pass for the model, but only updates the optimizer state allocated to it. Importantly, while every GPU carries out the entire forward and backward pass, it accesses parameters for an update from a broadcast of parameters from the other GPUs.</p><p>This approach does increase inter-GPU communication as GPUs need to broadcast updated gradients and parameters more frequently. However, this enhanced communication load is not drastically more than that in standard data parallelism where inter-GPU communication of gradients and parameter updates was already occurring.</p><p>The memory savings from this partitioning technique can be significant. If we consider that out of the 48GB memory, 36GB was being consumed by the optimizer state, by distributing these states we only need to store them once, leading to a memory saving of around 36GB * 3, totaling 108GB. Thus, this approach contributes to making the training of large models more efficient and mindful of resource utilization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DazIiRhrHmc-4oFcz8YizQ.png" /><figcaption>Memory savings and communication volume for the three stages of ZeRO compared with standard data parallel baseline. In the memory consumption formula, Ψ refers to the number of parameters in a model and <em>K</em> is the optimizer-specific constant term. As a specific example, we show the memory consumption for a 7.5B parameter model using <a href="https://arxiv.org/pdf/1412.6980.pdf">Adam</a> optimizer where <em>K</em>=12 on 64 GPUs. We also show the communication volume of ZeRO relative to the baseline.</figcaption></figure><h4>Parameter and gradient partitioning</h4><p>Training large language models can be further optimized by expanding the concept of partitioning to both parameters and gradients (fp16). This enhancement can be divided into three stages:</p><p>1.<strong> Optimizer State Partitioning (Pos)</strong>: This is the first step we explored previously, where we distribute the optimizer states across multiple GPUs. This strategy offers a 4x reduction in memory usage while keeping the communication volume the same as traditional data parallelism.</p><p>2. <strong>Gradient Partitioning (Pos+g)</strong>: The next step in optimization involves partitioning not only the optimizer states but also the gradients. This approach halves the memory requirement yet again, leading to an overall 8x reduction, while still maintaining the same level of communication as in standard data parallelism.</p><p>3. <strong>Parameter Partitioning (Pos+g+p)</strong>: The final stage encompasses partitioning the optimizer states, the gradients, and now the parameters across multiple GPUs. The memory reduction in this stage is directly proportional to the number of GPUs used (Nd). For example, distributing across 64 GPUs (Nd = 64) would lead to a 64x reduction in memory requirement. However, it’s worth noting that this does result in a moderate 50% increase in communication volume.</p><p>In the process of forward and backward propagation during model training, a scenario may arise where a GPU requires access to certain parameters or gradient partitions that it doesn’t currently possess. To obtain these, the GPU will need to request them from its counterparts, which results in an increase in inter-GPU communication volume. For a clearer visual explanation, a link to an illustrative animation from Microsoft Research has been provided below.</p><p><em>The efficiency and speed of communication in GPU-based systems rely heavily on the utilization of </em><a href="https://www.nvidia.com/en-in/design-visualization/nvlink-bridges/"><em>NVLink</em></a><em>, an interconnect technology designed to enable fast and direct communication between GPUs and between GPUs and CPUs. NVLink offers high bandwidth and energy efficiency, facilitating efficient data transfer and communication within the system. In addition, the introduction of </em><a href="https://www.nvidia.com/en-in/data-center/tensor-cores/"><em>tensor cores</em></a><em> in high-end GPUs is a significant advancement. Tensor cores are specifically designed to accelerate deep learning workloads. By enabling mixed-precision computations and providing hardware acceleration for matrix multiplication operations commonly used in deep learning models, tensor cores deliver substantial performance improvements.</em></p><p>These stages of partitions, part of what’s called ZeRO (short for Zero Redundancy Optimizer), aim to eradicate memory redundancies and maximize the utilization of the total memory capacity of a cluster. With all three stages activated, ZeRO can train a trillion-parameter model on just 1024 NVIDIA GPUs.</p><p>To provide a sense of scale, a trillion-parameter model with an optimizer like Adam in 16-bit precision would ordinarily require around 16 terabytes (TB) of memory to accommodate the optimizer states, gradients, and parameters. With ZeRO, this enormous task is managed more efficiently and resource-effectively.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fby86GQhKgKQ&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dby86GQhKgKQ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbd6145dc41aac523d949ae417015c5a/href">https://medium.com/media/dbd6145dc41aac523d949ae417015c5a/href</a></iframe><h3>References</h3><p>Other techniques to parallelize training</p><ul><li><a href="https://lilianweng.github.io/posts/2021-09-25-train-large/">How to Train Really Large Models on Many GPUs?</a></li><li><a href="https://arxiv.org/abs/1910.02054">ZeRO: Memory Optimizations Toward Training Trillion Parameter Models</a></li><li><a href="https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/">ZeRO &amp; DeepSpeed: New system optimizations enable training models with over 100 billion parameters - Microsoft Research</a></li><li><a href="https://www.microsoft.com/en-us/research/blog/zero-2-deepspeed-shattering-barriers-of-deep-learning-speed-scale/">DeepSpeed &amp; ZeRO-2: Shattering barriers of deep learning speed &amp; scale</a></li><li><a href="https://www.deepspeed.ai/training/">Training Overview and Features</a></li><li><a href="https://medium.com/@Shrishml/mixed-precision-training-all-a-data-scientist-needs-to-know-2660641c48d8">An intuitive understanding of mixed precision training</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FczgA-MbAdvA%3Fstart%3D4079%26feature%3Doembed%26start%3D4079&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DczgA-MbAdvA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FczgA-MbAdvA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6079f8f5d0aa3b4534f159f279e25ff7/href">https://medium.com/media/6079f8f5d0aa3b4534f159f279e25ff7/href</a></iframe><p>Thank you for taking the time to read my writing. If you enjoyed it, I invite you to follow me for future content. Additionally, feel free to connect with me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>.</p><p>You might like my other articles,</p><ul><li><a href="https://medium.com/@Shrishml/emergence-6d3eb6a27cbb">Emergence</a></li><li><a href="https://medium.com/@Shrishml/hiring-principles-for-a-super-data-team-1676d947531b">Hiring principles for a super data team</a></li><li><a href="https://medium.com/@Shrishml/learning-how-to-learn-6eacacbcdc05">Learning how to learn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e00d2e2f30a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-algorithmic-minds/breaking-the-gmemory-barrier-how-zero-revolutionizes-large-language-model-training-8e00d2e2f30a">Breaking the Memory Barrier: How ZeRO Revolutionizes Large Language Model Training</a> was originally published in <a href="https://medium.com/the-algorithmic-minds">The Algorithmic Minds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An intuitive understanding of mixed precision training]]></title>
            <link>https://medium.com/the-algorithmic-minds/mixed-precision-training-all-a-data-scientist-needs-to-know-2660641c48d8?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/2660641c48d8</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Sat, 06 May 2023 17:53:11 GMT</pubDate>
            <atom:updated>2024-02-08T12:08:02.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8jI9lqGKgXjE6D0S" /><figcaption>Photo by <a href="https://unsplash.com/@santesson89?utm_source=medium&amp;utm_medium=referral">Andrea De Santis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Deep learning models are well-known for their ability to achieve higher accuracy as their size increases. However, as models grow larger, they also require more memory and computing power to train. This increased computational requirement can result in higher costs, especially when using cloud computing services.</p><p>To overcome these challenges, the deep learning community has been exploring different ways to optimize the training process. One of the promising approaches by Sharan Narang is <a href="https://arxiv.org/pdf/1710.03740.pdf">mixed precision training</a>, which has gained popularity in recent years.</p><p>While there have been several attempts to train large models with reduced precision, all previous approaches have resulted in a non-trivial loss of accuracy for larger models. Mixed precision training, on the other hand, uses lower-precision data types for certain parts of the neural network while maintaining higher-precision data types for others. By doing so, it reduces the memory requirements of the neural network, speeds up the training process, and reduces costs.</p><p>The general idea behind mixed precision training is to carefully choose which parts of the neural network can use lower-precision data types without significantly impacting model accuracy. Although the technical details of mixed precision training can be complex, several resources are available to help you get started, such as the NVIDIA <a href="https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/index.html">Deep Learning Documentation</a>, which provides a good introduction to mixed precision training and offers guidance on how to implement it using their hardware and software tools.</p><p>Moreover, almost all deep learning frameworks, including TensorFlow and PyTorch, have built-in support for mixed precision training, making it easy to implement this technique in your own deep learning projects.</p><h4>Floating point precision</h4><p>Computers store numbers using the binary format, which represents numbers using only 0s and 1s. For example, with a single bit, we can represent only two unique numbers: 0 and 1. With two bits, we can represent four unique numbers: 00, 01, 10, and 11. By reserving the first bit to signify the sign of a number (0 for positive and 1 for negative), we can represent integers ranging from -1 to +2.</p><p>Using a commonly agreed convention, we can utilize the 4 unique numbers mentioned above to represent 4 unique decimal numbers as well, namely 0, 0.1, 0.2, and 0.3. This convention results in a range between 0 and 0.3 with a precision of 0.1. However, if we decrease the precision to 0.2, we can cover a larger range of numbers, such as 0, 0.2, 0.4, and 0.6. It’s essential to note that we can always represent 4 unique decimal numbers using only 2 bits. Therefore, increasing the precision limits our range, while decreasing it expands it.</p><p>Computers use 32 bits to represent a total of 2³² unique numbers, ranging from 0 to 2³²in integers. However, we use a lot of floating-point numbers (decimals) in computers, and it is impossible to represent a decimal number of arbitrary precision. Nonetheless, the limited precision of numbers is sufficient for most practical purposes.</p><p>To represent a decimal number in a computer, we use conventions. First, we write the decimal number in scientific notation (e.g., 0.0000001001011110101 is represented as .1001011110101 x 2⁸). Then, we use the first bit to save the sign of the number, followed by eight bits for the exponent(here it is 8) and the next 23 bits for the significand. In this example, the significand is .1001011110101.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ws6LDUcuzSpt858ee7S3mA.png" /><figcaption>Ranges of different floating precision formats(s<a href="https://cloud.google.com/blog/products/ai-machine-learning/bfloat16-the-secret-to-high-performance-on-cloud-tpus">ource</a>).</figcaption></figure><p><em>Note: In deep learning use cases, we are usually more concerned about the scale of gradients rather than the precision of numbers. This is where BF16, a number format developed by Google, comes into play. BF16 reserves more space for the exponent of a number at the cost of precision, making it more suitable for deep learning tasks. BF16 is typically deployed on specialized hardware such as TPUs and some of the latest GPUs to achieve optimal performance.</em></p><h3>What is mixed precision training?</h3><p>Using half-precision can significantly speed up the training and inference of deep learning models while saving memory. However, optimizing for speed and memory may come at the cost of model accuracy. To mitigate this issue, mixed precision training provides a hybrid approach that maintains accuracy while still benefiting from the speed gains of half-precision.</p><p>In mixed precision training, all tensors and arithmetic for forward and backward passes use reduced precision, such as FP16. No hyper-parameters, such as layer width or gradient clipping, are adjusted, and models trained using these techniques do not experience any loss of accuracy when compared to single-precision baselines.</p><p>The approach involves keeping the model parameters (weights) in single precision and performing all training processes in half-precision before updating the model in single precision again. By doing so, we can achieve more efficient computations and memory usage during training, while still ensuring that the final model retains the same level of accuracy as if it had been trained using full precision throughout the entire process.</p><h4>Keep a copy of the model weight</h4><p>The majority of weight updates, which are obtained by multiplying the learning rate with gradients, have a very small magnitude, often less than 6 e-8 as shown in the above figure. However, these small values would become zero in the FP16 format, making it unsuitable for performing the weight update process.</p><p>Therefore, it is advisable to maintain a single-precision master copy of the weights that accumulate the gradients after each optimizer step. This copy is then converted back to half-precision format for the forward- and back-propagation steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*F1pr9aKo4kFd-B9i-lnqVQ.png" /><figcaption>During the training of a neural network, the Forward pass, Backward pass, and Gradient calculations are performed in half-precision to speed up the process. However, the updated weights are then converted back to single precision before being updated to the model. This ensures that the model remains accurate by preventing any loss of precision due to repeated rounding off of values during training (s<a href="https://arxiv.org/pdf/1710.03740.pdf">ource</a>).</figcaption></figure><p>A simple algorithm is,</p><ol><li>Maintain a primary copy of weights in FP32.</li><li>For each iteration:</li></ol><ul><li>Make an FP16 copy of the weights.</li><li>Forward propagation (FP16 weights and activations).</li><li>Backward propagation (FP16 weights, activations, and their gradients).</li><li>Complete the weight update (including gradient clipping, etc.).</li></ul><h4>Scaling loss to scale gradients</h4><p>While half-precision (FP16) can accelerate deep learning model training, there is a limitation to this approach. The histogram of the weights and activation gradients shown below reveals that many values fall outside the FP16 range, causing a considerable number of gradients to become zero. As a result, the model’s accuracy decreases.</p><p>To overcome this issue, the solution is to apply scaling to the loss function by multiplying the loss by S (added in logarithmic scale). This scaling operation causes all gradients to also scale by S (using the chain rule), which allows them to fit within the FP16 range. However, it is essential to unscale the gradients before updating the model weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMGJR1JAFHXL--Y5rhwLSg.png" /><figcaption><em>Histogram of activation gradient magnitudes throughout FP32 training of Multibox SSD network. Both x- and y-axes are logarithmic.</em></figcaption></figure><p>The updated algorithm will be like this,</p><ol><li>Maintain a primary copy of weights in FP32.</li><li>For each iteration:</li></ol><ul><li>Make an FP16 copy of the weights.</li><li>Forward propagation (FP16 weights and activations).</li><li>Multiply the resulting loss with the scaling factor <em>S</em>.</li><li>Backward propagation (FP16 weights, activations, and their gradients).</li><li>Multiply the weight gradient by 1/<em>S</em>.</li><li>Complete the weight update (including gradient clipping, etc.).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yTF-BQRtbLt2VtOFQvu8Q.png" /><figcaption>When using half-precision (FP16), the loss function can sometimes diverge. However, the FP16 training loss is replicating the FP32 training loss if we keep scaling the loss. This allows for the benefits of half-precision to be leveraged without compromising the accuracy of the model. (s<a href="https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/index.html">ource</a>).</figcaption></figure><h4>How it performs?</h4><p>Mixed precision training has proven to be a highly effective approach for deep learning, achieving up to 8x faster computation times without sacrificing model accuracy. However, this approach does require slightly more memory(1.5x) to store weights in both half and single-precision formats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jy4GXVQRgYO9rMt9Vj1jiw.png" /><figcaption>Accuracy for some of the deep learning models in classification tasks (<a href="https://arxiv.org/pdf/1710.03740.pdf">Source</a>). We observe that model accuracy is more or less the same with mixed precision(FP16 &amp; FP32) to baseline(FP32) methods.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*KWBuJu8h30Dvvj95icPVNg.png" /><figcaption>Accuracy for some of the deep learning models in object detection tasks (<a href="https://arxiv.org/pdf/1710.03740.pdf">Source</a>).</figcaption></figure><h4>Python Implementations</h4><p>All popular deep learning framework has it implemented. For example, keras implementation of mixed precision training and auto-scale of loss can be implemented as below.</p><pre>opt = tf.keras.optimizers.Adam()<br>opt = tf.train.experimental.enable_mixed_precision_graph_rewrite(opt)<br>model.compile(loss=loss, optimizer=opt)<br>model.fit(…)</pre><p>The <a href="https://www.deepspeed.ai/docs/config-json/#fp16-training-options">deepspeed</a> Python package by Microsoft has incorporated mixed precision training into its frameworks, which allows for different settings and loss scaling options.</p><p>Here are some examples of configurations that include available json keys.</p><pre>&quot;bf16&quot;: {<br>   &quot;enabled&quot;: true<br> }</pre><pre>&quot;fp16&quot;: {<br>    &quot;enabled&quot;: true,<br>    &quot;auto_cast&quot;: false,<br>    &quot;loss_scale&quot;: 0,<br>    &quot;initial_scale_power&quot;: 16,<br>    &quot;loss_scale_window&quot;: 1000,<br>    &quot;hysteresis&quot;: 2,<br>    &quot;min_loss_scale&quot;: 1<br>}</pre><p>We can also use <a href="https://www.pytorchlightning.ai/index.html">PyTorch lightning</a> to implement mixed precision training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmrIHCTO3dXNU0Z2dPZSBg.png" /></figure><h4>References and some other good articles</h4><ul><li><a href="https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/index.html">Mixed Precision Training</a></li><li><a href="https://arxiv.org/pdf/1710.03740.pdf">Mixed Precision Training (arxiv)</a></li><li><a href="https://moocaholic.medium.com/fp64-fp32-fp16-bfloat16-tf32-and-other-members-of-the-zoo-a1ca7897d407">FP64, FP32, FP16, BFloat16, TF32, and Other Members of the Zoo</a></li><li><a href="https://cloud.google.com/blog/products/ai-machine-learning/bfloat16-the-secret-to-high-performance-on-cloud-tpus">BFloat16: The Secret to High Performance on Cloud TPUs</a></li><li><a href="https://www.coursera.org/lecture/machine-learning-modeling-pipelines-in-production/benefits-and-process-of-quantization-WAjyJ">Benefits and Process of Quantization — Week 2: Model Resource Management Techniques</a></li><li><a href="https://www.deepspeed.ai/docs/config-json/#fp16-training-options">DeepSpeed Configuration JSON Schema</a></li></ul><p>Thank you for taking the time to read my writing. If you enjoyed it, I invite you to follow me for future content. Additionally, feel free to connect with me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>.</p><p>You might like my other articles,</p><ul><li><a href="https://medium.com/@Shrishml/emergence-6d3eb6a27cbb">Emergence</a></li><li><a href="https://medium.com/@Shrishml/hiring-principles-for-a-super-data-team-1676d947531b">Hiring principles for a super data team</a></li><li><a href="https://medium.com/@Shrishml/learning-how-to-learn-6eacacbcdc05">Learning how to learn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2660641c48d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-algorithmic-minds/mixed-precision-training-all-a-data-scientist-needs-to-know-2660641c48d8">An intuitive understanding of mixed precision training</a> was originally published in <a href="https://medium.com/the-algorithmic-minds">The Algorithmic Minds</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning how to learn]]></title>
            <link>https://medium.com/@Shrishml/learning-how-to-learn-6eacacbcdc05?source=rss-70b699ae9114------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eacacbcdc05</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Shrish]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 13:14:43 GMT</pubDate>
            <atom:updated>2023-03-21T13:22:16.509Z</atom:updated>
            <content:encoded><![CDATA[<p>As technology continues to evolve rapidly, it is essential for individuals to keep up with the latest skills and knowledge to remain competitive in the job market. Continuous learning and upskilling have become the norm rather than an option for many professionals, as industries and job requirements constantly change.</p><p>“Learning How to Learn: Powerful mental tools to help you master tough subjects” by <a href="https://www.coursera.org/learn/learning-how-to-learn">Dr. Barbara Oakley</a> is an excellent practical course, which I will try to summarize in this article.</p><p>This course provides learners with practical strategies to overcome common obstacles to effective learning, such as procrastination, distractions, and difficulty retaining information. It offers insights into how the brain works and provides techniques to optimize learning, such as the Pomodoro technique, which involves breaking up study sessions into short, focused bursts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XNTvsZTx4jQumw-Z" /><figcaption>Photo by <a href="https://unsplash.com/@davidsonluna?utm_source=medium&amp;utm_medium=referral">D A V I D S O N L U N A</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Focus is the key</h3><p>In today’s fast-paced world where instant gratification and social media distractions are prevalent, maintaining focus for an extended period can be a challenge. However, it is crucial to eliminate all distractions while learning to maximize the effectiveness of the learning process.</p><p>One effective method for improving focus is the Pomodoro technique, which involves breaking up study sessions into 25-minute intervals of focused work, followed by a 10-minute break. This technique helps to maintain productivity while allowing for rest and recovery periods.</p><p>The psychological concept of “<a href="https://www.amazon.in/Flow-Psychology-Experience-Perennial-Classics/dp/0061339202">flow</a>” is also essential for effective learning. Flow occurs when a person is fully immersed in a task and feels a sense of control and enjoyment. Engaging in flow activities not only enhances productivity but also leads to increased well-being and quality of life.</p><p>In summary, it is important to prioritize focus and eliminate distractions while learning. The Pomodoro technique can be a useful tool for maintaining focus, and the concept of flow can enhance productivity and overall well-being. By implementing these strategies, individuals can optimize their learning and achieve greater success in their careers and personal lives.</p><h3>Take a break</h3><p>Effective learning requires a balance between two modes of thinking: focused thinking and diffuse thinking. Focused thinking is when you concentrate on a specific task, while diffuse thinking is when your mind wanders and makes connections between seemingly unrelated topics. Both modes are essential for effective learning, and the course teaches how to balance the two for optimal results.</p><p>The focused mode of thinking is responsible for completing tasks and solving problems. This mode is activated when we concentrate on a particular task and block out distractions. On the other hand, the diffused mode of thinking is activated when we take a break from a task and allow our mind to wander. This mode is responsible for generating new ideas, making connections between concepts, and strengthening what has been learned in the focused mode.</p><p>Taking a break from focused thinking and engaging in diffused thinking activities such as walking, exercising, or taking a nap, allows the diffused mode of thinking to assimilate and consolidate the learning that has taken place in the focused mode. This can lead to a deeper understanding and retention of the material.</p><p>In addition, sleep plays a crucial role in consolidating memories and enhancing learning. We can improve the quality of sleep with healthy habits, such as creating a comfortable sleep environment, avoiding electronic devices before bedtime, and sticking to a regular sleep schedule.</p><h3>Intermittent learning</h3><p>Breaking up learning into smaller, more manageable chunks is a highly effective way to improve retention and comprehension. Research has shown that learning for one hour per day over the course of 12 days has far better learning outcomes than studying for 12 hours in one day.</p><p>When we learn, our brain creates neural connections, or circuits, that reinforce the information being learned. These circuits take time to form and strengthen, which is why cramming large amounts of information into one study session is not as effective. By spacing out learning over several days, the brain has time to settle the information into the reinforced circuits created during the learning process.</p><p>Moreover, cramming can lead to stress and anxiety, which can negatively impact learning and retention. When we are stressed, our brain releases cortisol, a hormone that can interfere with memory formation and recall.</p><p>By breaking up learning into smaller chunks, learners can also reduce the feeling of overwhelm and increase their motivation to learn.</p><h3>let&#39;s do it!</h3><p>Learning is not complete until you can apply what you have learned to solve related problems. Simply memorizing information without understanding how to use it in real-life situations will not guarantee that you have truly learned it.</p><p>In recent years, there has been a positive trend toward project-based learning. This approach embeds basic concepts into projects that provide learners with an opportunity to apply their knowledge and skills to solve real-world problems.</p><p>By engaging in project-based learning, learners can also develop a deeper understanding of the material they are studying, as they are actively applying it to solve problems. This type of learning allows learners to see the practical applications of what they have learned, which can be motivating and increase their confidence in their abilities</p><h3>Revisit</h3><p>Knowledge is not linear; it is circular and unique to each individual. Our brain stores information in a way that is influenced by our past experiences, knowledge, and memories. While courses and books are written in a linear fashion because of the linear flow of time.</p><p>Revisiting the material multiple times is crucial for solidifying learning and connecting the dots between different concepts. Through repeated exposure, learners can reinforce their understanding of the material and develop a more comprehensive knowledge base. In fact, revising some subjects as many as 3 to 4 times can greatly improve confidence and mastery of the subject matter.</p><p>Additionally, learning new subjects outside of one’s main area of focus can improve long-term learning and creativity. By exposing oneself to a variety of topics and perspectives, learners can broaden their understanding of the world and make connections between seemingly unrelated concepts.</p><h3>Zombie Mode</h3><p>According to the book “Atomic Habits,” creating strong habit systems is essential for automating the most challenging tasks of the day. As an example, during my physics undergraduate studies, I found solving questions in I.E. Irodov’s book to be a difficult task. To tackle this challenge, I developed a system of solving just two questions every morning. By consistently following this system for a year, I was able to complete the book successfully.</p><p>It is important to acknowledge that our energy and willpower are limited resources, and relying on them alone to accomplish everything we need to do is not sustainable. It is better to create habits that allow us to put some of our more challenging tasks on autopilot, freeing up willpower and energy for other activities. This is sometimes referred to as “zombie mode” or “habit mode,” and it can be a powerful way to save and allocate your willpower and energy effectively. By creating strong habit systems, we can make progress toward our goals while still conserving our mental and emotional resources.</p><h3>Get bored for a while</h3><p>Learning new things can be challenging for the brain, as it involves creating new neural pathways and reinforcing existing ones. While we may not always be motivated to learn, it is important to avoid constant entertainment, as this can hinder our ability to learn difficult concepts.</p><p>During an experiment, participants were placed in a room with no activities except a button that delivered electric shocks to themselves. The goal was to observe how individuals cope with boredom, and the results were surprising. Despite claiming that they would pay money to avoid being shocked with electricity, 67% of men and 25% of women willingly pressed the button to inflict the shock on themselves. This study shows how humans struggle with boredom and how it can lead to extreme measures to avoid it. From a personal experience, if an individual finds it challenging to learn something, it is essential to eliminate all distractions and allow yourself to be bored. This process will allow the brain to rewire itself and focus on learning the material.</p><p>From personal experience, the process of learning complex concepts like machine learning and mathematics can be challenging, even for me with a background in physics. However, by eliminating distractions(or other cheap dopamine hits) like social media and spending an ample amount of time in a state of boredom, the brain will gradually kneel and begin to find learning entertaining as it prefers electric shock over boredom.</p><p>Thank you for taking the time to read my writing. If you enjoyed it, I invite you to follow me for future content. Additionally, feel free to connect with me on <a href="https://www.linkedin.com/in/shrishml/">LinkedIn</a>.</p><p>You might like my other articles,</p><ul><li><a href="https://medium.com/@Shrishml/emergence-6d3eb6a27cbb">Emergence</a></li><li><a href="https://medium.com/@Shrishml/hiring-principles-for-a-super-data-team-1676d947531b">Hiring principles for a super data team</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eacacbcdc05" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>