<?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 Wing Lian on Medium]]></title>
        <description><![CDATA[Stories by Wing Lian on Medium]]></description>
        <link>https://medium.com/@winglian?source=rss-f93310bf954------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zstGJQHYeaYegYk6.jpeg</url>
            <title>Stories by Wing Lian on Medium</title>
            <link>https://medium.com/@winglian?source=rss-f93310bf954------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:16:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@winglian/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[QLoRA finetuning Llama 3.1 405B with Axolotl with ~256GB system RAM]]></title>
            <link>https://medium.com/@winglian/qlora-finetuning-llama-3-1-405b-with-axolotl-with-256gb-system-ram-c2474a3d3fa5?source=rss-f93310bf954------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2474a3d3fa5</guid>
            <category><![CDATA[finetune-llm]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[qlora]]></category>
            <dc:creator><![CDATA[Wing Lian]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 12:14:10 GMT</pubDate>
            <atom:updated>2024-07-29T13:39:54.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IYd77ii4ct8HVBPjDbnDg.png" /></figure><p>In the excitement of Llama’s 405B model, few have been able to finetune it without multiple H100 nodes. Snowflake has <a href="https://www.snowflake.com/engineering-blog/fine-tune-llama-single-node-snowflake/">claimed</a> it should be possible using their modified ZeRO-2 implementation, but I’ve not been able to reproduce this.</p><p>In the various attempts to finetune 405B on a single node, I found ~1.6–1.8TB of system RAM is needed for offloading as currently transformers attempts to offload the weights to cpu on each rank. We know from <a href="https://www.answer.ai/posts/2024-03-06-fsdp-qlora.html">answer.ai</a> that we only need to do this on rank0 and load the parameter weights to the meta device on all other ranks.</p><pre>pip uninstall transformers<br>pip install &quot;transformers @ git+https://github.com/winglian/transformers.git@fsdp-meta-sharding&quot;</pre><p>Also, when loading pre-quantized weights, bitsandbytes doesn’t set the quant_state needed for FSDP. <a href="https://github.com/matthewdouglas">@matthewdouglas</a> will have a PR up for this fix soon. In the meantime, you can use the branch below to compile from source.</p><pre>pip uninstall bitsandbytes<br>git clone https://github.com/winglian/bitsandbytes.git<br>cd bitsandbytes<br>pip install -r requirements-dev.txt<br>cmake -DCOMPUTE_BACKEND=cuda -S .<br>make<br>pip install -e .</pre><p>Finally, in your <a href="https://github.com/OpenAccess-AI-Collective/axolotl">axolotl</a> path, you’ll want to use the branch updates-20240728.</p><pre># in axolotl path, /workspace/axolotl on runpod<br>git fetch &amp;&amp; git checkout updates-20240728<br>huggingface-cli download hugging-quants/Meta-Llama-3.1-405B-BNB-NF4-BF16<br>accelerate launch -m axolotl.cli.train examples/llama-3/qlora-fsdp-405b.yaml</pre><p>At the lower end of finetuning @ 512 context length, this needs ~51GB VRAM per GPU for finetuning. I firmly believe that once <a href="https://github.com/pytorch/pytorch/issues/124480">fused gemm+xentropy loss kernels</a> are solved, anyone will be able to finetune 405B on 8xL40S’s or similar GPUs with 48GB VRAM. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2474a3d3fa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Augmenting Classification Datasets with Mistral Large for Deeper Reasoning]]></title>
            <link>https://medium.com/@winglian/augmenting-classification-datasets-with-mistral-large-for-deeper-reasoning-99dea57bd1d4?source=rss-f93310bf954------2</link>
            <guid isPermaLink="false">https://medium.com/p/99dea57bd1d4</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Wing Lian]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 16:48:29 GMT</pubDate>
            <atom:updated>2024-03-05T16:48:29.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9Hztdfvhobt2euBVWyGUg.jpeg" /></figure><p>As the landscape AI continues to innovate, the capabilities of these large language models becomes increasingly evident, especially to companies looking to leverage the potential of these LLMs. Often times we hear about how the key component to the effectiveness of these models is in fact the quality of the underlying datasets on which we are training the models. However, for most scenarios, the existing datasets, particularly those used for classification tasks, lack the ability to elicit the underlying reasoning these models are capable of when used for more complex real world scenarios. In light of this, we are going to explore how we can leverage high quality models such as Mistral Large to augment and enhance a classification dataset so that we can interact with the finetuned model in a more conversational manner.</p><p>For this walkthrough, we’re going to start off with a fairly common ML use case: sentiment analysis. What we often find with sentiment analysis datasets are that they only include the sentiment labels, typically positive, neutral, and negative. We are going to use the <a href="https://huggingface.co/datasets/financial_phrasebank">financial phrasebank dataset</a> available on HuggingFace which consists of sentences from financial news and has been subsequently labeled by multiple annotators (which I assume to mean human annotators). This particular dataset has multiple subsets based on the level of agreement of the annotators; 50%, 75% and 100% agreement.</p><p>Upon inspection of this dataset (available in the <a href="https://huggingface.co/datasets/financial_phrasebank/viewer">dataset viewer</a>), we see there are only two fields, sentence and label. The labels are numeric, mapping to values of 0 =&gt; negative, 1 =&gt;neutral, and 2 =&gt; positive. In order to augment this dataset, we can leverage the existing labels that are available as a guide for the teacher model, in this case Mistral Large, to create a reasoning for the sentiment label, knowing the correct answer or ground truth. For the training dataset, we will use the sentences_allagree subset which contains ~2200 rows. The prompt that we use to generate the reasoning is:</p><pre>prompt = f```Sentence: {row[&quot;sentence&quot;]}<br>    <br>    Ground Truth: {label_map[row[&quot;label&quot;]]}<br>    <br>    Analyze the sentence above and determine if the sentiment of the sentence <br>is neutral, positive or negative. Explain your reasoning in detail before <br>stating your conclusion of the sentiment. The conclusion should simply be <br>the string value of the sentiment. Your conslusion must match the provided <br>ground truth.<br>    <br>    Respond with JSON with fields `reasoning` and `conclusion`, i.e. <br>{{ &quot;reasoning&quot;: &quot;...&quot;, &quot;conclusion&quot;: &quot;neutral|positive|negative&quot; }}.<br>```</pre><p>To simplify parsing the response into it’s various parts; reasoning and conclusion, we can use the instructor <a href="https://jxnl.github.io/instructor/">library</a> to parse the response according to a structure that we can define in pydantic.</p><pre>from pydantic import BaseModel<br><br>class AugmentedLabels(BaseModel):<br>    reasoning: str<br>    conclusion: Literal[&quot;neutral&quot;, &quot;positive&quot;, &quot;negative&quot;]</pre><p>While we could simply point to Mistral’s API directly for the inference, I opted to use litellm as an abstraction so that we could also leverage <a href="https://openrouter.ai/">OpenRouter</a>. OpenRouter acts as a proxy to various hosted models, and depending on the model that you wish to inference against, it can find the best pricing available. In our case, Mistral Large is only really available from Mistral, but adding this layer in now allows us to easily swap out the underlying model for augmentation without fewer additional code changes.</p><pre>MODEL_NAME = &quot;openrouter/mistralai/mistral-large&quot;</pre><p>From here, we simply need to loop over the dataset with our prompt, inference against Mistral Large, create an updated dataset based with the reasoning and upload the new dataset to HuggingFace.</p><p>For the evaluation part of the dataset, I opted to use the sentences_75agree subset, generate reasoning and conclusion labels from Mistral Large and only include rows where Mistral Large’s conclusion matched the annotator majority’s label. In this case, the prompt was simply:</p><pre>prompt = f&quot;&quot;&quot;Sentence: {row[&quot;sentence&quot;]}<br>        <br>    Analyze the sentence above and determine if the sentiment of the sentence <br>is neutral, positive or negative. Explain your reasoning in detail before <br>stating your conclusion of the sentiment. The conclusion should simply be <br>the string value of the sentiment.<br>    <br>    Respond with JSON with fields `reasoning` and `conclusion`, i.e. <br>{{ &quot;reasoning&quot;: &quot;...&quot;, &quot;conclusion&quot;: &quot;neutral|positive|negative&quot; }}.<br>&quot;&quot;&quot;</pre><p>These augmented <a href="https://huggingface.co/datasets/winglian/financial_phrasebank_augmented/viewer">training</a> and <a href="https://huggingface.co/datasets/winglian/financial_phrasebank_augmented-validation/viewer">validation</a> datasets have been made public on HuggingFace.</p><p>Next, we move on to finetuning a base model to respond using <a href="https://github.com/OpenAccess-AI-Collective/axolotl">Axolotl</a>. Axolotl is a LLM finetuning tool that allows anyone to quickly and easily define the various configuration and hyperparameter settings to finetune a model. For this particular experiment, I used Mistral Instruct v0.2 because there seemed to be an issue downloading the base Mistral v0.1 model from HuggingFace.</p><p>While the actual YAML used to finetune this model and dataset is available on <a href="https://wandb.ai/oaaic/financial-phrasebank-reasoning/runs/sr0jnndo/files/axolotl_config_8aszh7xf.yml">Weights &amp; Biases</a>, here are the important parameters:</p><pre>base_model: mistralai/Mistral-7B-Instruct-v0.2<br>load_in_8bit: false<br><br>chat_template: chatml<br>datasets:<br>  - path: winglian/financial_phrasebank_augmented<br>    type: sharegpt<br>    split: train<br>    strict: false<br>test_datasets:<br>  - path: winglian/financial_phrasebank_augmented-validation<br>    type: sharegpt<br>    split: train<br>    strict: false<br><br>adapter: lora<br>sequence_len: 768<br><br>lora_r: 32<br>lora_alpha: 16<br>lora_dropout: 0.1<br>lora_target_modules:<br>  - gate_proj<br>  - down_proj<br>  - up_proj<br>  - q_proj<br>  - v_proj<br>  - k_proj<br>  - o_proj<br>lora_modules_to_save:<br>  - embed_tokens<br>  - lm_head<br><br>gradient_accumulation_steps: 4<br>micro_batch_size: 2<br>num_epochs: 3<br>optimizer: adamw_bnb_8bit<br>lr_scheduler: cosine<br>learning_rate: 0.00001<br><br>train_on_inputs: false<br>bf16: auto<br>gradient_checkpointing: true<br>flash_attention: true<br>warmup_steps: 10<br><br>special_tokens:<br>  eos_token: &quot;&lt;|im_end|&gt;&quot;<br>tokens:<br>  - &quot;&lt;|im_start|&gt;&quot;</pre><p>You can see from the YAML that we opted to finetune a LoRA adapter for this dataset as I wanted to use a RTX4090 so that this sort of work could be reproduced in a more accessible manner. In fact, this single finetuning job took less than 30 minutes to run, although I did experiment with a few hyperparameters to ensure this was optimal. The various experiments were tracked and available on <a href="https://wandb.ai/oaaic/financial-phrasebank-reasoning">Weights &amp; Biases.</a></p><p><a href="https://wandb.ai/oaaic/financial-phrasebank-reasoning">oaaic</a></p><p>We ran the experiment on a cloud RTX4090 GPU <a href="https://runpod.io/gsc?template=v2ickqhz9s&amp;ref=6i7fkpdz">on RunPod</a> using the <a href="https://hub.docker.com/r/winglian/axolotl-cloud/tags">winglian/axolotl-cloud:main-latest</a> <a href="https://hub.docker.com/r/winglian/axolotl-cloud/tags">image from Docker</a>. Once we SSH’ed into the container, we simply ran</p><pre>accelerate launch -m axolotl.cli.train mistral-sentiment.yml</pre><p>from the CLI. Because this particular training is a LoRA, we needed to merge the LoRA adapter into the base model after training with</p><pre>python -m axolotl.cli.merge_lora mistral-sentiment.yml --save_safetensors=True</pre><p>The merged model was uploaded to HuggingFace and is publicly available at <a href="https://huggingface.co/winglian/financial-phrasebank-sentiment-reasoning">https://huggingface.co/winglian/financial-phrasebank-sentiment-reasoning</a>.</p><p>Here is a quick test of our model using some unseen data from the 50% agree subset of the financial_phrasebank dataset.</p><pre>import torch<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br>device = &quot;cuda&quot; # the device to load the model onto<br><br>model = AutoModelForCausalLM.from_pretrained(&quot;winglian/financial-phrasebank-sentiment-reasoning&quot;, attn_implementation=&quot;flash_attention_2&quot;, torch_dtype=torch.bfloat16)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;winglian/financial-phrasebank-sentiment-reasoning&quot;)<br><br>sentence = &quot;With the new production plant the company would increase its capacity to meet the expected increase in demand and would improve the use of raw materials and therefore increase the production profitability.&quot;<br><br>messages = [<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Sentence: {sentence}\n\nAnalyze the sentence above and determine if the sentiment of the sentence is neutral, positive or negative.&quot;},<br>]<br><br>encodeds = tokenizer.apply_chat_template(messages, return_tensors=&quot;pt&quot;)<br><br>model_inputs = encodeds.to(device)<br>model.to(device)<br><br>generated_ids = model.generate(model_inputs, max_new_tokens=1000, do_sample=True)<br>decoded = tokenizer.batch_decode(generated_ids)<br>print(decoded[0])</pre><pre>The sentence describes the positive outcomes of the company constructing a <br>new production plant. Specifically, it mentions an increase in capacity, <br>a more efficient use of raw materials, and an improvement in production <br>profitability as benefits of the new plant. The sentence does not contain <br>any negative words or phrases, nor does it mention any problems or <br>challenges that the company is facing. Therefore, the sentiment of the <br>sentence is positive.</pre><p>As demonstrated, we’ve been able to take an existing classification dataset, enrich the dataset with reasoning from Mistral Large as a teacher model, and finetune a model to explain the reasoning for classification tasks. As many may be aware, this is very similar to Microsfot’s <a href="https://arxiv.org/abs/2306.02707">Orca paper</a> and is the basis for the production of the <a href="https://huggingface.co/datasets/Open-Orca/OpenOrca">OpenOrca dataset</a> that I helped to work on. Of course, augmentation of such datasets is not limited to classification tasks, but this should serve as an example of how we can use existing general models like GPT-4, Claude and others to enrich these datasets.</p><p>The code use to augment the dataset is available at <a href="https://github.com/winglian/financial-phrasebank-augmentation">https://github.com/winglian/financial-phrasebank-augmentation</a>.</p><p>I’d like to thank all of our contributors and supporters of Axolotl to help get Axolotl to where it is today. Additionally, I’d like to thank <a href="https://a16z.com/ai/">a16z</a> for supporting the OSS AI community and Axolotl with their AI grant. If you’d like to learn more about Axolotl, join our <a href="https://discord.gg/UYfTqF9KS4">Discord community</a> or reach out on X/Twitter <a href="https://twitter.com/winglian">@winglian</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99dea57bd1d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inference any LLM with serverless in 15 minutes]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@winglian/inference-any-llm-with-serverless-in-15-minutes-69eeb548a41d?source=rss-f93310bf954------2"><img src="https://cdn-images-1.medium.com/max/1024/1*lRf0Al2v0DHQ7pq_W_cg7Q.png" width="1024"></a></p><p class="medium-feed-snippet">Uncovering the efficiency of deploying large language models with Runpod&#x2019;s serverless infrastructure</p><p class="medium-feed-link"><a href="https://medium.com/@winglian/inference-any-llm-with-serverless-in-15-minutes-69eeb548a41d?source=rss-f93310bf954------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@winglian/inference-any-llm-with-serverless-in-15-minutes-69eeb548a41d?source=rss-f93310bf954------2</link>
            <guid isPermaLink="false">https://medium.com/p/69eeb548a41d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Wing Lian]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 10:40:10 GMT</pubDate>
            <atom:updated>2023-06-04T10:40:10.213Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to unplug from work: 7 tips for a healthy work life balance]]></title>
            <link>https://medium.com/@winglian/how-to-unplug-from-work-7-tips-for-a-healthy-work-life-balance-62f387d596be?source=rss-f93310bf954------2</link>
            <guid isPermaLink="false">https://medium.com/p/62f387d596be</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[work-life-balance]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[mental-health]]></category>
            <dc:creator><![CDATA[Wing Lian]]></dc:creator>
            <pubDate>Fri, 15 Apr 2022 02:21:47 GMT</pubDate>
            <atom:updated>2022-04-15T02:29:03.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrdNSq_FhB_s4TmpA5uFJg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema">Kelly Sikkemma</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>We all know that work life balance is important, but it’s not always easy to achieve. Especially in today’s tech culture where we are constantly connected to work via our smartphones. It can be tough to disconnect from work and relax after a long day, but it’s crucial for our mental and physical health. In this article, we will go over the steps you need to take to disconnect from work and achieve a healthy work life balance!</p><p><strong>Set work hours.</strong> If you work from home, this may be a little harder to do, but it’s important to set some boundaries. Let your family and friends know when your work hours are so they respect your time. During these work hours, turn off all distractions like your phone, TV, and social media. This way you can focus on work and get it done efficiently. If your work calendar allows you to specify your work hours, make sure to do so. This will help prevent work from creeping into your personal time.</p><p><strong>Take breaks.</strong> When you’re working hard, it’s important to take a few minutes here and there to relax and rejuvenate yourself. Get up and walk around, stretch, or grab a healthy snack. Taking short breaks will help you stay focused and refreshed so you can power through your workday. One common method of enforcing breaks is to use the pomodoro technique. The pomodoro technique is when you work for 25 minutes and then take a five-minute break. After four pomodoros, you can take a longer break of 20–30 minutes. This loose framework for setting up breaks helps to ensure that you’re taking them regularly.</p><p><strong>Know when to say no.</strong> One of the main reasons we have trouble disconnecting from work is because we feel like we always have to be available. We need to learn to say no to work requests that are outside of our work hours or that we simply don’t have time for. If you’re constantly saying yes to work, it will start to pile up and you’ll never be able to disconnect. Learning how to say no is an important skill for maintaining a healthy work life balance.</p><p><strong>Leave work at work.</strong> When your work hours are over, close your laptop, and put it away. If you have the option to, leave your laptop at work in a locked drawer. But if you’re like many who work remotely, this isn’t always an option. In that case, make sure to have a clear work space in your home so you can close the door on work when your work day is done. This will help create a physical and mental separation between work and home life.</p><p><strong>Disconnect from work after hours.</strong> This means no checking work email, no logging into work Slack, and no working on projects outside of work hours. If you need to do any of these things for your job, set specific times for them during the week so you’re not constantly thinking about work. And when those times are over, disconnect completely! This may be easier said than done, but it’s important to try to achieve a healthy balance between work and personal life. Many smartphones may have the option to completely snooze notifications from work-related apps after a certain time.</p><p><strong>Unplug completely from work every once in a while.</strong> This may mean taking a day off or even going on vacation. When you’re on vacation, make sure not to check work email or take work calls unless it’s absolutely necessary. This is your time to relax and recharge, so make the most of it!</p><p><strong>Take some time for yourself every day.</strong> This can be something as simple as taking a few minutes to meditate or journal, or going for a walk outside. It’s important to do something that relaxes you and clears your mind so you can focus on work when it’s time to work, and enjoy your personal life when it’s time for that.</p><p>A healthy work life balance is essential for both your mental and physical health, so make sure to take the steps necessary to achieve it! Thanks for reading. I hope these tips help you unplug from work and achieve a healthy work life balance. Namaste.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62f387d596be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>