<?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 Hamish Dickson on Medium]]></title>
        <description><![CDATA[Stories by Hamish Dickson on Medium]]></description>
        <link>https://medium.com/@_mishy?source=rss-5dad3f818ede------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*sHVFTIYz-kgJ5tP7.jpg</url>
            <title>Stories by Hamish Dickson on Medium</title>
            <link>https://medium.com/@_mishy?source=rss-5dad3f818ede------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:53:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_mishy/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[How to build an AI powered labelling tool — Part 1, the UI]]></title>
            <link>https://medium.com/@_mishy/how-to-build-an-ai-powered-labelling-tool-part-1-the-ui-45580e864102?source=rss-5dad3f818ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/45580e864102</guid>
            <category><![CDATA[labelling]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hamish Dickson]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 16:31:45 GMT</pubDate>
            <atom:updated>2024-03-31T16:31:45.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4byITX6BqYn8sWN7PRuZw.png" /></figure><h3>How to build an AI powered labelling tool — Part 1, the UI</h3><p>Welcome to this two part blog post where we’re going to build an AI powered labelling tool.</p><p>You can find the code for everything here on colab: <a href="https://colab.research.google.com/drive/15rgkY9AEavX31xzQlBByE55iIAc0_GaP?usp=sharing">https://colab.research.google.com/drive/15rgkY9AEavX31xzQlBByE55iIAc0_GaP?usp=sharing</a></p><p>Before we dive in, a quick bit of motivation. I’m an AI freelancer and have been working in data, machine learning and AI for over 15 years. I’ve worked for huge companies, and tiny 5 person startups. The common theme to everything I’ve every worked on is: no one has nicely labelled data! (And to be honest, that’s ok! It means you are probably working on something new!)</p><p>So what do you do in this situation? Well let me show you the approach I’ve pieced together over time. We have a few goals here:</p><ul><li>To have a tool that’s easy to change</li><li>Have a tool which you can run in most situations easily</li><li>To have a tool which will learn, letting you label as much data as possible quickly and accurately</li></ul><p>We’re going to do this in two parts, in this first part we’ll create the UI using Jupyter Widgets and in part 2 we will build a model to help us label as we go.</p><h3>Let’s start with some data</h3><p>It’s always helpful to have a real problem to focus the discussion around. After a very brief search on Hugging Face, I’ve found <a href="https://huggingface.co/datasets/dair-ai/emotion">this</a></p><pre>from datasets import load_dataset<br><br>dataset = load_dataset(&quot;dair-ai/emotion&quot;)</pre><p>This is an NLP classification task where we take tweets and classify them into one of anger, fear, joy, love, sadness, and surprise.</p><pre>|    | text                                                                                                         |   label |<br>|---:|:-------------------------------------------------------------------------------------------------------------|--------:|<br>|  0 | i didnt feel humiliated                                                                                      |       0 |<br>|  1 | i can go from feeling so hopeless to so damned hopeful just from being around someone who cares and is awake |       0 |<br>|  2 | im grabbing a minute to post i feel greedy wrong                                                             |       3 |</pre><p>There is nothing special in our approach with using an NLP classification task, everything I’m about to walk through can be changed to work with images or tabular data or almost any other problem you may have.</p><h3>Our First Widget</h3><p>We’re going to use Jupyter notebook widgets to act as our UI.</p><p>Why aren’t we just using streamlit you may ask? Well for the simple reason that in most real world situations data is very protected and you have to use a remote machine to access it, getting approval to open up ports for things like streamlit can be problematic, but most data/security teams are perfectly happy with jupyter notebooks (normally via kubeflow/sagemaker/vertex ai).</p><p>We need a way of taking rows of data and displaying them to our user, so that’s do that</p><p>First we’re going to write a function to sample from our dataset</p><pre>def get_random_tweet():<br>    &quot;&quot;&quot;Sample an tweet from the dataset, this is just a basline example. Some ideas to improve are:<br>    - make sure you&#39;ve not already picked it<br>    - over/undersample based on fields<br>    - include any labels you may have already (for example you migh pre-label with an LLM)<br>    &quot;&quot;&quot;<br>    row = df.sample(1).iloc[0]<br><br>    return {<br>        &quot;text&quot;: row[&#39;text&#39;]<br>    }</pre><p>All this is doing is randomly picking out a tweet, how you sample your data for labelling can be complicated but a good first place to start is often “find a dataset which looks like the data you’ll eventually run on and pick at random”</p><p>Now we need a way to run this and show the result to the user. We do this by:</p><ul><li>creating a HTML wrapper to hold the text</li><li>creating a button, which when pressed calls our sampler, then displays the results</li></ul><pre># Initialize the tweet display widget<br>tweet_display = widgets.HTML(<br>    value=&quot;&quot;,<br>    placeholder=&#39;Tweet text will appear here&#39;,<br>    description=&#39;&#39;,<br>)<br><br>def display_tweet(tweet):<br>    body_text_with_newlines_preserved = tweet[&#39;text&#39;][:200].replace(&#39;\n&#39;, &#39;&lt;br&gt;&#39;)<br>    formatted_text = f&quot;&lt;strong&gt;Text:&lt;/strong&gt;&lt;br&gt;{body_text_with_newlines_preserved}&lt;br&gt;&lt;br&gt;&quot;<br>    tweet_display.value = formatted_text<br><br>def get_next_tweet(b):<br>    # Placeholder for getting the next tweet - implement this according to your data retrieval logic<br>    global current_tweet<br>    current_tweet = get_random_tweet()<br>    display_tweet(current_tweet)<br><br>get_next_button = widgets.Button(description=&quot;Get Next Tweet&quot;)<br>get_next_button.on_click(get_next_tweet)</pre><p>To use all of this week need to create a ui_layout and then display it to the user. We do this by adding the components we want to display to the children input</p><pre>ui_layout = widgets.VBox(children=[tweet_display, get_next_button])<br><br>display(ui_layout)</pre><p>We should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkNvquMDI7HFkp6zLzQp-w.png" /></figure><p>And on click, we should see something a little like the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRYjIvhDi4S58QjnIrBfYA.png" /></figure><p>Great stuff! We have built the main part of our UI already!</p><h3>Let’s now build the (manual) labeller</h3><p>We need something to store our labels. We’re just going to do this with a list. Put this before the code above</p><pre>labels = []</pre><p>Now, because we are building a classifier we need some way to:</p><ul><li>select the class</li><li>save it to our labels</li></ul><p>The easiest way to select a class is with RadioButtons</p><pre># Here we create the radio buttons to pick from<br>class_labels = [&quot;anger&quot;, &quot;fear&quot;, &quot;joy&quot;, &quot;love&quot;, &quot;sadness&quot;, &quot;surprise&quot;]<br>class_radiobuttons = widgets.RadioButtons(options=class_labels)</pre><p>to use this we simply add to our ui_layout</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtwm2WUkAXNuP4lciYFMuQ.png" /></figure><p>Now we need a way to save our class prediction.</p><p>To get the selected value from a Radio Button all you need to call is class_radiobuttons.value</p><p>So let’s create a button which when pressed gets this value and saves it along with our tweet to our labels</p><pre>def commit_tweet(b):<br>    current_tweet[&#39;emotion&#39;] = class_radiobuttons.value<br>    labels.append(current_tweet)<br><br>commit_button = widgets.Button(description=&quot;Commit&quot;)<br>commit_button.on_click(commit_tweet)</pre><p>Remember, for the user to see our changes we must update our ui_layout and display once more</p><pre>ui_layout = widgets.VBox(children=[tweet_display, class_radiobuttons, commit_button, get_next_button])<br><br>display(ui_layout)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4byITX6BqYn8sWN7PRuZw.png" /><figcaption>Our completed manual labeller</figcaption></figure><h3>Conclusion</h3><p>OK that’s it for now, we have built a labeller which will let us sample from a dataset, pick a class for each time and save the label. The key things we want from this is:</p><ul><li>run anywhere jupyter is allowed (Vertex AI, SageMaker, KubeFlow)</li><li>to have a tool which will let us label quickly, ideally without typing too much out</li></ul><p>Come back for part 2, where I’ll show you how to extend this with a model. The model will learn as we label, at the end the goal will be to have blazingly fast labelling (mostly committing the model prediction and getting next)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45580e864102" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Gradient Checkpointing with Hugging Face models]]></title>
            <link>https://medium.com/@_mishy/how-to-use-gradient-checkpointing-with-hugging-face-models-9821bd8b51b1?source=rss-5dad3f818ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/9821bd8b51b1</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Hamish Dickson]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 10:50:58 GMT</pubDate>
            <atom:updated>2024-03-22T10:50:58.205Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you are GPU poor and would like to train a huge model, how do you do it?</p><p>Well your first approach is probably to use gradient accumulation, using multiple forward passes for each backward pass. When you average out the losses you can get very similar results to a bigger batch.</p><p>But … what if you can’t even do a single forward pass? You just don’t have enough GPU vRAM?</p><p>Gradient checkpointing is an easy way to get around this. Here is what you need to do, when you declare your model just add model.gradient_checkpointing_enable()</p><pre>import transformers<br># note: you need to import this line, it&#39;s missing from almost all documentation<br>import torch.utils.checkpoint<br><br>model = transformers.AutoModel.from_pretrained(&quot;my_huge_model&quot;)<br>model.gradient_checkpointing_enable()</pre><p>And that’s it, you get much more freedom to train your model.</p><p>So what is this doing? Well the short answer is we are trading speed for memory and we are doing it by moving some of our intermediate data off of our GPU and into memory.</p><p>You should play about with batch sizes here to try and find a balance between speed and batch size.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9821bd8b51b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Hugging Face Transformer models without downloading the pretrained weights]]></title>
            <link>https://medium.com/@_mishy/using-hugging-face-transformer-models-without-downloading-the-pretrained-weights-a9bc21b952c0?source=rss-5dad3f818ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9bc21b952c0</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Hamish Dickson]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 09:12:30 GMT</pubDate>
            <atom:updated>2024-03-17T09:12:30.126Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you have been given the task of classifying product descriptions into categories. You have the data and compute to do what you need and because you are awesome at your job you do this in record time.</p><h3>The Simple Case</h3><p>You will probably be using Hugging Face’s Transformers library for this and you will probably start off with a simple model which looks like the following:</p><pre>import transformers<br><br>model_name = &quot;microsoft/deberta-v3-xsmall&quot;<br>where_my_weights_live = &quot;my_save_location&quot;<br><br># create your tokenizer and model from the pretrained weights<br>tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)<br><br># let&#39;s pretend there are 10 labels<br>model = transformers.AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=10)<br><br># ... train your model ...<br><br># finally save everything - this is all you need to do<br>tokenizer.save_pretrained(where_my_weights_live)<br>model.save_pretrained(where_my_weights_live)</pre><p>Now it’s time to put this in production and the engineering team asks for you help to make sure this is done properly. What does this look like?</p><p>Well this is quite easy, you can basically just do this</p><pre>import transformers<br><br>where_my_weights_live = &quot;my_save_location&quot;<br><br>tokenizer = transformers.AutoTokenizer.from_pretrained(where_my_weights_live)<br>model = transformers.AutoModelForSequenceClassification.from_pretrained(where_my_weights_live)</pre><p>It’s easy to read, efficient and everyone is happy. Good job!</p><h3>A More Realistic Example</h3><p>In reality while the default models are very good you are likely to want to modify them. For example, imagine we want to insert some product features into our model. We would have to declare our own model in this case.</p><p>It could look a little like this</p><pre>import torch<br>import transformers<br><br>class ProductClassifier(torch.nn.Module):<br>    def __init__(self, model_name, num_features, num_labels):<br>        super(ProductClassifier, self).__init__()<br>        <br>        self.model = transformers.AutoModel.from_pretrained(model_name)<br><br>        self.fc_features = torch.nn.Linear(n_features, n_features)<br><br>        model_hidden_size = self.model.config.hidden_size<br>        self.fc_out = torch.nn.Linear(model_hidden_size + num_features, num_labels)<br><br>    def forward(self, inputs, features):<br>        model_outputs = self.model(**inputs)<br>        model_outputs = model_outputs.last_hidden_state[:, 0, :]<br><br>        feature_outputs = self.fc_features(features)<br><br>        outputs = torch.cat([model_outputs, feature_outputs], dim=1)<br><br>        return self.fc_out(outputs)</pre><p>You would have to save this a little differently than the default models, it would look a bit like this</p><pre># declare our models and train our code<br><br>where_my_weights_live = &quot;my_save_location&quot;<br><br>tokenizer.save_pretrained(where_my_weights_live)<br><br>torch.save(model.state_dict(), f&quot;{where_my_weights_live}/pytorch_model.bin&quot;)</pre><p>You can no longer just do model.save_pretrained instead we have to save the state_dict (ie the model weights).</p><p>Now, how do you use this?</p><p>Well, what’s the most obvious way to do this? It’s probably something like this?</p><pre>model_name = ...   # same as what we trained<br>num_features = ... # same as what we trained<br>num_labels = ...   # same as what we trained<br><br># pytorch doesn&#39;t save the model definition, so we have to declare it<br>class ProductClassifier(torch.nn.Module):<br>    def __init__(self, model_name, num_features, num_labels):<br>        super(ProductClassifier, self).__init__()<br>        <br>        self.model = transformers.AutoModel.from_pretrained(model_name)<br><br>        self.fc_features = torch.nn.Linear(n_features, n_features)<br><br>        model_hidden_size = self.model.config.hidden_size<br>        self.fc_out = torch.nn.Linear(model_hidden_size + num_features, num_labels)<br><br>    def forward(self, inputs, features):<br>        model_outputs = self.model(**inputs)<br>        model_outputs = model_outputs.last_hidden_state[:, 0, :]<br><br>        feature_outputs = self.fc_features(features)<br><br>        outputs = torch.cat([model_outputs, feature_outputs], dim=1)<br><br>        return self.fc_out(outputs)<br><br># now we can load the weights<br>model = ProductClassifier(model_name, num_features, num_labels)<br>model.load_state_dict(torch.load(where_my_weights_live, map_location=torch.device(&#39;cpu&#39;)))<br>model.eval() # don&#39;t forget this!</pre><p>This will probably work but something subtle happens — this will download the original model weights from Hugging Face!</p><pre>self.model = transformers.AutoModel.from_pretrained(model_name)</pre><p>This line in our is the problematic line. It will download the weights from hugging face!</p><p>This isn’t something that’s going to break your code but it’s going to make it very slow to initialise and also you are downloading some weights that you will never actually use.</p><p>Instead, can we initialise the model without downloading these weights?</p><h3>Using from_config</h3><p>We can do this</p><pre>model_name = ...   # same as what we trained<br>num_features = ... # same as what we trained<br>num_labels = ...   # same as what we trained<br><br># pytorch doesn&#39;t save the model definition, so we have to declare it<br>class ProductClassifier(torch.nn.Module):<br>    def __init__(self, model_name, num_features, num_labels):<br>        super(ProductClassifier, self).__init__()<br>        self.model_config = transformers.AutoConfig.from_pretrained(model_name)<br>        self.model = transformers.AutoModel.from_config(config=self.model_config)<br><br>        self.fc_features = torch.nn.Linear(n_features, n_features)<br><br>        model_hidden_size = self.model.config.hidden_size<br>        self.fc_out = torch.nn.Linear(model_hidden_size + num_features, num_labels)<br><br>    def forward(self, inputs, features):<br>        model_outputs = self.model(**inputs)<br>        model_outputs = model_outputs.last_hidden_state[:, 0, :]<br><br>        feature_outputs = self.fc_features(features)<br><br>        outputs = torch.cat([model_outputs, feature_outputs], dim=1)<br><br>        return self.fc_out(outputs)<br><br># now we can load the weights<br>model = ProductClassifier(model_name, num_features, num_labels)<br>model.load_state_dict(torch.load(where_my_weights_live, map_location=torch.device(&#39;cpu&#39;)))<br>model.eval() # don&#39;t forget this!</pre><p>Here instead of using AutoModel.from_pretrained we are using AutoModel.from_config this will create a model from the config without downloading the pretrained weights, this is much better</p><p>But in this case we are still going to the internet and downloading the config. It would be better to do this without going to internet</p><p>Ideally we would change our training setup so it looked more like this</p><pre>import torch<br>import transformers<br><br>model_name = ...<br>num_features = ...<br>num_labels = ...<br><br>model_config = transformers.AutoConfig.from_pretrained(model_name)<br>tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)<br><br>class ProductClassifier(torch.nn.Module):<br>    def __init__(self, model_config, num_features, num_labels):<br>        super(ProductClassifier, self).__init__()<br>        self.model = transformers.AutoModel.from_config(config=model_config)<br><br>        self.fc_features = torch.nn.Linear(n_features, n_features)<br><br>        model_hidden_size = self.model.config.hidden_size<br>        self.fc_out = torch.nn.Linear(model_hidden_size + num_features, num_labels)<br><br>    def forward(self, inputs, features):<br>        model_outputs = self.model(**inputs)<br>        model_outputs = model_outputs.last_hidden_state[:, 0, :]<br><br>        feature_outputs = self.fc_features(features)<br><br>        outputs = torch.cat([model_outputs, feature_outputs], dim=1)<br><br>        return self.fc_out(outputs)<br><br><br>model = ProductClassifier(model_config, num_features, num_labels)<br><br># train the model<br><br># now you have to save one more thing, the model config<br>model_config.save_pretrained(where_my_weights_live)<br>tokenizer.save_pretrained(where_my_weights_live)<br>torch.save(model.state_dict(), f&quot;{where_my_weights_live}/pytorch_model.bin&quot;)</pre><p>Finally our production code is just this!</p><pre>where_my_weights_live = <br><br><br>tokenizer = transformers.AutoTokenizer.from_pretrained(where_my_weights_live)<br>model_config = transformers.AutoConfig.from_pretrained(where_my_weights_live)<br><br><br>model = ProductClassifier(model_config, num_features, num_labels)<br>model.load_state_dict(torch.load(where_my_weights_live, map_location=torch.device(&#39;cpu&#39;)))<br>model.eval() # don&#39;t forget this!</pre><p>And now we can use our model without downloading anything!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9bc21b952c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>