<?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 Shubham Kumar Singh on Medium]]></title>
        <description><![CDATA[Stories by Shubham Kumar Singh on Medium]]></description>
        <link>https://medium.com/@shubham.ksingh.cer14?source=rss-78f678a92dc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BJfhriaOE77XB3bgq3yhcQ.jpeg</url>
            <title>Stories by Shubham Kumar Singh on Medium</title>
            <link>https://medium.com/@shubham.ksingh.cer14?source=rss-78f678a92dc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:05:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shubham.ksingh.cer14/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[Using BERT: Strategies for text classification]]></title>
            <link>https://medium.com/@shubham.ksingh.cer14/using-bert-strategies-for-text-classification-32f9c211576d?source=rss-78f678a92dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/32f9c211576d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Shubham Kumar Singh]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 14:21:00 GMT</pubDate>
            <atom:updated>2025-08-03T13:44:05.960Z</atom:updated>
            <content:encoded><![CDATA[<p>BERT (Bidirectional Encoder Representations from Transformers) revolutionized NLP by enabling models to capture context in language through its bidirectional attention mechanism. In this blog, we’ll dive deep into leveraging BERT for various classification tasks. We’ll explore different strategies, implementations, and best practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSdzLRhH6mBJysaCfqkHgA.png" /></figure><h3>What is BERT?</h3><p>BERT is a transformer-based model pretrained on vast amounts of text data. Unlike traditional embedding methods, BERT captures contextual relationships from both directions in the text simultaneously, making it highly effective for understanding language nuances.</p><p>Read more about BERT here: <a href="https://jalammar.github.io/illustrated-bert/">https://jalammar.github.io/illustrated-bert/</a></p><h3>Classification Tasks with BERT</h3><p>We’ll explore three approaches:</p><ol><li><strong>Fine-tuning BERT directly</strong></li><li><strong>Using BERT as a feature extractor</strong></li><li><strong>Freezing BERT and training a custom MLP</strong></li></ol><h3>1. Fine-Tuning BERT Directly</h3><p>This approach involves training BERT end-to-end for classification. <strong>(Training all layers)</strong></p><p><strong>What it means: </strong>When you fine-tune BERT, you’re adjusting <em>every single parameter</em> in the model — both the transformer layers and the final classification layer. Essentially, you’re customizing BERT’s internal representations specifically to your task.</p><p><strong>Pros:</strong></p><ul><li>Best possible performance (with enough data)</li><li>Highly adaptable to your specific domain</li><li>Takes full advantage of BERT’s internal complexity</li></ul><p><strong>Cons:</strong></p><ul><li>Requires larger labeled datasets (typically thousands of examples)</li><li>Higher computational cost (GPU required)</li><li>Potential risk of “catastrophic forgetting,” where BERT loses its pretrained general knowledge if you aren’t careful with hyperparameters and regularization.</li></ul><p><strong>When to choose this:</strong></p><ul><li>You have a substantial labeled dataset</li><li>You need the highest accuracy possible</li><li>You’re comfortable with GPU training and careful experimentation</li></ul><pre>from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments<br>from datasets import load_dataset</pre><pre># Load dataset and tokenizer<br>dataset = load_dataset(&#39;imdb&#39;)<br>tokenizer = BertTokenizer.from_pretrained(&#39;bert-base-uncased&#39;)</pre><pre>def tokenize(batch):<br>    return tokenizer(batch[&#39;text&#39;], padding=True, truncation=True)</pre><pre>tokenized_dataset = dataset.map(tokenize, batched=True)<br>model = BertForSequenceClassification.from_pretrained(&#39;bert-base-uncased&#39;)</pre><pre>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    evaluation_strategy=&quot;epoch&quot;,<br>    num_train_epochs=3,<br>    per_device_train_batch_size=16,<br>    per_device_eval_batch_size=16<br>)</pre><pre>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_dataset[&#39;train&#39;],<br>    eval_dataset=tokenized_dataset[&#39;test&#39;]<br>)</pre><pre>trainer.train()</pre><h3>2. Using BERT as a Feature Extractor</h3><p>Instead of fine-tuning BERT, we use its embeddings as fixed features and train a separate classifier (e.g., logistic regression).</p><p><strong>What it means:</strong></p><p>You use BERT’s pretrained embeddings directly without any additional training. You simply feed your text through BERT once, grab the embeddings (usually the [CLS] embedding), and then train a separate lightweight classifier like Logistic Regression, SVM, or LightGBM on top.</p><p><strong>Pros:</strong></p><ul><li>Fastest and simplest approach</li><li>Lowest computational and memory overhead</li><li>No risk of catastrophic forgetting or overfitting</li></ul><p><strong>Cons:</strong></p><ul><li>Usually lower performance compared to fine-tuning</li><li>Limited ability to adapt to nuances of your domain</li></ul><p><strong>When to choose this:</strong></p><ul><li>Quick prototyping or limited compute resources</li><li>Small datasets (hundreds of examples)</li><li>You prefer classical machine-learning pipelines</li></ul><pre>import torch<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score</pre><pre>bert_model = BertForSequenceClassification.from_pretrained(&#39;bert-base-uncased&#39;, output_hidden_states=True)<br>bert_model.eval()</pre><pre># Extract features<br>def extract_features(batch):<br>    inputs = tokenizer(batch[&#39;text&#39;], return_tensors=&#39;pt&#39;, padding=True, truncation=True)<br>    with torch.no_grad():<br>        outputs = bert_model(**inputs)<br>    cls_embeddings = outputs.hidden_states[-1][:,0,:].numpy()<br>    return cls_embeddings</pre><pre>X_train = extract_features(dataset[&#39;train&#39;][:1000])<br>y_train = dataset[&#39;train&#39;][&#39;label&#39;][:1000]<br>X_test = extract_features(dataset[&#39;test&#39;][:500])<br>y_test = dataset[&#39;test&#39;][&#39;label&#39;][:500]</pre><pre>clf = LogisticRegression()<br>clf.fit(X_train, y_train)<br>y_pred = clf.predict(X_test)</pre><pre>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))</pre><h3>3. Freezing BERT and Training a Custom MLP</h3><p>Here, we freeze BERT weights and train a multilayer perceptron (MLP) using the [CLS] token embeddings for classification.</p><p><strong>What it means:</strong></p><p>You keep BERT frozen (no weight updates) and train only a small neural network (MLP) on top of the BERT embeddings. You still leverage BERT’s contextualized embeddings, but now your task-specific layer has more flexibility and learning capacity compared to traditional ML classifiers.</p><p><strong>Pros:</strong></p><ul><li>Balances performance and computational cost</li><li>Little risk of forgetting, as original BERT weights remain untouched</li><li>Good adaptation capability to your task/domain</li></ul><p><strong>Cons:</strong></p><ul><li>Slightly lower accuracy ceiling than full fine-tuning (especially on large, diverse datasets)</li><li>Still requires neural network training (though simpler than full fine-tuning)</li></ul><p><strong>When to choose this:</strong></p><ul><li>Small to medium-sized datasets (1k–10k examples)</li><li>Moderate compute resources</li><li>Desire good performance without extensive GPU cost or tuning</li></ul><pre>import torch.nn as nn<br>import torch.optim as optim</pre><pre>class BERT_MLP(nn.Module):<br>    def __init__(self, bert_model, hidden_size=768, num_classes=2):<br>        super(BERT_MLP, self).__init__()<br>        self.bert = bert_model<br>        for param in self.bert.parameters():<br>            param.requires_grad = False<br>        self.mlp = nn.Sequential(<br>            nn.Linear(hidden_size, 256),<br>            nn.ReLU(),<br>            nn.Dropout(0.3),<br>            nn.Linear(256, num_classes)<br>        )</pre><pre>    def forward(self, input_ids, attention_mask):<br>        outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)<br>        cls_token = outputs.hidden_states[-1][:,0,:]<br>        return self.mlp(cls_token)</pre><pre>model = BERT_MLP(bert_model)<br>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.Adam(model.mlp.parameters(), lr=1e-4)</pre><pre># Example training loop for brevity<br>for epoch in range(3):<br>    model.train()<br>    inputs = tokenizer(dataset[&#39;train&#39;][:1000][&#39;text&#39;], return_tensors=&#39;pt&#39;, padding=True, truncation=True)<br>    labels = torch.tensor(dataset[&#39;train&#39;][:1000][&#39;label&#39;])</pre><pre>    outputs = model(inputs[&#39;input_ids&#39;], inputs[&#39;attention_mask&#39;])<br>    loss = criterion(outputs, labels)</pre><pre>    optimizer.zero_grad()<br>    loss.backward()<br>    optimizer.step()</pre><pre>    print(f&quot;Epoch {epoch+1}, Loss: {loss.item()}&quot;)</pre><h3>How to choose?</h3><ul><li><strong>Large dataset and compute available?</strong> → <strong>Fine-tune fully.</strong></li><li><strong>Quick experiments or limited compute?</strong> → <strong>Use BERT as a feature extractor.</strong></li><li><strong>Balance of accuracy, speed, and simplicity?</strong> → <strong>Freeze BERT and train a small MLP.</strong></li></ul><h3>Actual code I used</h3><ol><li>Approach 1 was to use built-in BertForSequenceClassification with a built in MLP attached on a phishing task</li></ol><pre># %pip install evaluate</pre><pre>import evaluate<br>import numpy as np<br>from datasets import DatasetDict, Dataset, load_dataset<br>from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments</pre><pre>dataset_dict = load_dataset(&quot;shawhin/phishing-site-classification&quot;)</pre><pre>bert_model = BertForSequenceClassification.from_pretrained(&#39;bert-base-uncased&#39;, output_hidden_states=True, num_labels=2)<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>bert_model.base_model.eval()  # Putting oly base BERT in eval mode as we want classifier drop-out to still work</pre><pre># define text preprocessing<br>def tokenize(batch):<br>    return tokenizer(batch[&quot;text&quot;], padding=&quot;max_length&quot;, truncation=True, max_length=256)</pre><pre>tokenized_ds = dataset_dict.map(tokenize, batched=True)</pre><pre>## We want to train the classifier only and NOT the full BERT, hence freezing BERT layers</pre><pre># freeze all base model parameters<br>for name, param in bert_model.base_model.named_parameters():<br>    param.requires_grad = False<br>    <br>    <br># load metrics<br>accuracy = evaluate.load(&quot;accuracy&quot;)<br>auc_score = evaluate.load(&quot;roc_auc&quot;)</pre><pre>def compute_metrics(eval_pred):<br>    # get predictions<br>    predictions, labels = eval_pred<br>    <br>    # apply softmax to get probabilities<br>    probabilities = np.exp(predictions) / np.exp(predictions).sum(-1, <br>                                                                 keepdims=True)<br>    # use probabilities of the positive class for ROC AUC<br>    positive_class_probs = probabilities[:, 1]<br>    # compute auc<br>    auc = np.round(auc_score.compute(prediction_scores=positive_class_probs, <br>                                     references=labels)[&#39;roc_auc&#39;],3)<br>    <br>    # predict most probable class<br>    predicted_classes = np.argmax(predictions, axis=1)<br>    # compute accuracy<br>    acc = np.round(accuracy.compute(predictions=predicted_classes, <br>                                     references=labels)[&#39;accuracy&#39;],3)<br>    <br>    return {&quot;Accuracy&quot;: acc, &quot;AUC&quot;: auc}<br>    <br># hyperparameters<br>lr = 2e-4<br>batch_size = 8<br>num_epochs = 10</pre><pre>training_args = TrainingArguments(<br>    output_dir=&quot;bert-phishing-classifier-test&quot;,<br>    learning_rate=lr,<br>    per_device_train_batch_size=batch_size,<br>    per_device_eval_batch_size=batch_size,<br>    num_train_epochs=num_epochs,<br>    logging_strategy=&quot;epoch&quot;,<br>    eval_strategy=&quot;epoch&quot;,<br>    save_strategy=&quot;epoch&quot;,<br>    load_best_model_at_end=True,<br>)</pre><pre>trainer = Trainer(<br>    model=bert_model,<br>    args=training_args,<br>    train_dataset=tokenized_ds[&quot;train&quot;],<br>    eval_dataset=tokenized_ds[&quot;test&quot;],<br>    compute_metrics=compute_metrics,<br>)</pre><pre># Train<br>trainer.train()</pre><p>With the above code, training for one epoch on CPU took around 10–15 minutes.</p><p>To make it faster, I moved it to GPU on Colab → made it 10x faster. Then output looked something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*5dEAaVKMAsxA31m4NPRBcA.png" /></figure><p>One way to make it more faster is to <strong>Pre-compute [CLS] embeddings once → R</strong>un BERT <strong>once</strong>, cache the 768-d vectors, then train the MLP on those tensors only</p><p><strong>One simple trick to 10x the speed.</strong></p><p>But that can’t be done using BertForSequenceClassification. Hence I used the follwoing code and then <strong>1 epoch took less than a second on a T4 GPU.</strong></p><pre>from transformers import BertTokenizer, BertModel<br>from datasets import load_dataset<br>from torch.utils.data import Dataset, DataLoader, TensorDataset<br>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>from sklearn.metrics import accuracy_score, roc_auc_score</pre><pre># 1. Load data<br>dataset = load_dataset(&quot;shawhin/phishing-site-classification&quot;)<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>bert = BertModel.from_pretrained(&quot;bert-base-uncased&quot;)<br>bert.eval()<br>bert.to(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)</pre><pre># 2. Tokenize<br>def tokenize(batch):<br>    return tokenizer(batch[&quot;text&quot;], padding=&quot;max_length&quot;, truncation=True, max_length=256, return_tensors=&quot;pt&quot;)</pre><pre># 3. Extract [CLS] embeddings<br>def extract_cls_embeddings(data):<br>    cls_embeds = []<br>    labels = []<br>    with torch.no_grad():<br>        for example in data:<br>            tokens = tokenize(example)<br>            input_ids = tokens[&quot;input_ids&quot;].to(device)<br>            attention_mask = tokens[&quot;attention_mask&quot;].to(device)<br>            output = bert(input_ids=input_ids, attention_mask=attention_mask)<br>            cls = output.last_hidden_state[:, 0, :]  # Get [CLS]<br>            cls_embeds.append(cls.cpu())<br>            labels.append(example[&quot;labels&quot;]) # Changed &#39;label&#39; to &#39;labels&#39;<br>    return torch.cat(cls_embeds), torch.tensor(labels)<br>    <br>    <br>X_train, y_train = extract_cls_embeddings(dataset[&quot;train&quot;])<br>X_test, y_test = extract_cls_embeddings(dataset[&quot;test&quot;])</pre><pre>train_data = TensorDataset(X_train, y_train)<br>test_data = TensorDataset(X_test, y_test)</pre><pre>train_loader = DataLoader(train_data, batch_size=16, shuffle=True)<br>test_loader = DataLoader(test_data, batch_size=16)</pre><pre>class MLPClassifier(nn.Module):<br>    def __init__(self, in_dim=768, hidden_dim=256, out_dim=2):<br>        super().__init__()<br>        self.model = nn.Sequential(<br>            nn.Linear(in_dim, hidden_dim),<br>            nn.ReLU(),<br>            nn.Dropout(0.1),<br>            nn.Linear(hidden_dim, out_dim)<br>        )</pre><pre>    def forward(self, x):<br>        return self.model(x)</pre><pre>model = MLPClassifier().to(device)<br>optimizer = optim.Adam(model.parameters(), lr=1e-4)<br>criterion = nn.CrossEntropyLoss()</pre><pre>def evaluate(model, loader, criterion):<br>    model.eval()<br>    all_preds, all_probs, all_labels = [], [], []<br>    val_loss = 0<br>    with torch.no_grad():<br>        for x, y in loader:<br>            x, y = x.to(device), y.to(device)<br>            logits = model(x)<br>            loss = criterion(logits, y)<br>            val_loss += loss.item()</pre><pre>            probs = torch.softmax(logits, dim=1)<br>            preds = torch.argmax(probs, dim=1)</pre><pre>            all_preds.extend(preds.cpu().numpy())<br>            all_probs.extend(probs[:, 1].cpu().numpy())<br>            all_labels.extend(y.cpu().numpy())</pre><pre>    acc = accuracy_score(all_labels, all_preds)<br>    auc = roc_auc_score(all_labels, all_probs)<br>    avg_val_loss = val_loss / len(loader)<br>    return avg_val_loss, acc, auc</pre><pre># Train<br>for epoch in range(10):<br>    model.train()<br>    total_loss = 0<br>    for x, y in train_loader:<br>        x, y = x.to(device), y.to(device)<br>        optimizer.zero_grad()<br>        logits = model(x)<br>        loss = criterion(logits, y)<br>        loss.backward()<br>        optimizer.step()<br>        total_loss += loss.item()</pre><pre>    avg_train_loss = total_loss / len(train_loader)<br>    val_loss, acc, auc = evaluate(model, test_loader, criterion)<br>    print(f&quot;Epoch {epoch+1} | Train Loss: {avg_train_loss:.4f} | Val Loss: {val_loss:.4f} | Accuracy: {acc:.4f} | AUC: {auc:.4f}&quot;)</pre><p>This produced the following results:</p><p>Epoch 1 | Train Loss: 0.3070 | Val Loss: 0.3192 | Accuracy: 0.8489 | AUC: 0.9369 Epoch 2 | Train Loss: 0.2897 | Val Loss: 0.3036 | Accuracy: 0.8556 | AUC: 0.9430 Epoch 3 | Train Loss: 0.2795 | Val Loss: 0.2955 | Accuracy: 0.8644 | AUC: 0.9454 Epoch 4 | Train Loss: 0.2668 | Val Loss: 0.2870 | Accuracy: 0.8756 | AUC: 0.9481 Epoch 5 | Train Loss: 0.2537 | Val Loss: 0.3025 | Accuracy: 0.8778 | AUC: 0.9489 Epoch 6 | Train Loss: 0.2481 | Val Loss: 0.2804 | Accuracy: 0.8822 | AUC: 0.9516 Epoch 7 | Train Loss: 0.2398 | Val Loss: 0.2872 | Accuracy: 0.8822 | AUC: 0.9536 Epoch 8 | Train Loss: 0.2340 | Val Loss: 0.2670 | Accuracy: 0.8800 | AUC: 0.9551 Epoch 9 | Train Loss: 0.2278 | Val Loss: 0.2746 | Accuracy: 0.8911 | AUC: 0.9556 Epoch 10 | Train Loss: 0.2205 | Val Loss: 0.2608 | Accuracy: 0.8911 | AUC: 0.9572</p><h3>Recommendations</h3><ul><li><strong>Fine-tuning</strong>: Best accuracy but computationally intensive.</li><li><strong>Feature extraction</strong>: Quick to implement and efficient for simpler tasks.</li><li><strong>Frozen BERT + MLP</strong>: Good balance between complexity and accuracy.</li></ul><h3>Key take-aways</h3><ol><li><strong>Fine-tuning all layers</strong> unlocks the full representational power of BERT, but demands more data, GPU hours, and hyper-parameter care to prevent over-fitting or forgetting.</li><li><strong>Feature extraction</strong> is the safest, fastest baseline. It keeps BERT frozen and lets you swap in any downstream classifier, but performance is capped by the frozen embeddings.</li><li><strong>Freezing BERT + a small MLP head</strong> is a middle ground: you gain task-specific non-linearity with minimal risk and cost. It’s a strong default for small-to-medium projects or rapid iterations.</li></ol><p>Choose the strategy that balances <strong>dataset size, compute budget, and required accuracy</strong> for your scenario.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32f9c211576d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plan and Execute: AI Agents Architecture]]></title>
            <link>https://medium.com/@shubham.ksingh.cer14/plan-and-execute-ai-agents-architecture-f6c60b5b9598?source=rss-78f678a92dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6c60b5b9598</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Shubham Kumar Singh]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 19:35:32 GMT</pubDate>
            <atom:updated>2024-12-12T19:35:32.904Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I will talk about the “<strong>plan-and-execute</strong>” style agent design. These agents promise a number of improvements over traditional Reasoning and Action (ReAct)-style agents.</p><h4><strong>Limitations of ReAct Architecture</strong></h4><p>While ReAct (Reasoning + Acting) has been a popular paradigm, it struggles in some critical areas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*vQmjMMElmIH5HTfxyAqaOA.png" /><figcaption>Traditional ReAct Styled architecture.</figcaption></figure><ul><li><strong>Bottleneck Blues</strong>: Imagine an agent that stops and thinks after every single action, like a car that needs to restart its engine at every traffic light. That’s ReAct for you — sequential and painfully slow.</li><li><strong>Memory Mayhem</strong>: These agents forget everything they’ve learned the moment a task is complete. It’s like having a brilliant assistant with short-term memory loss.</li></ul><h3>Enter the Plan-and-Execute Paradigm</h3><p>Plan-and-Execute Paradigm promises a number of improvements:</p><ol><li>First of all, they can execute multi-step workflow <em>faster,</em> since the larger agent doesn’t need to be consulted after each action.</li><li>Second, they offer cost savings over ReAct agents. If LLM calls are used for sub-tasks, they typically can be made to smaller, domain-specific models.</li><li>Third, they can perform better overall (in terms of task completions rate and quality) by forcing the planner to explicitly “think through” all the steps required to accomplish the entire task.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*VBuh9ajccuCNzYin-F4zVw.png" /><figcaption>Plan and execute agent architecture. Source: <a href="https://blog.langchain.dev/planning-agents/">this</a> page</figcaption></figure><h4><strong>What is the Plan-and-Execute Architecture?</strong></h4><p>The <em>Plan-and-Execute</em> architecture consists of two basic components:</p><ol><li><strong>Planner</strong>, which prompts an LLM to generate a multi-step plan to complete a large task.</li><li><strong>Executor(s)</strong>, which accept the user query and a step in the plan and invoke 1 or more tools to complete that task.</li></ol><h4><strong>Workflow:</strong></h4><ol><li>The planner generates a multi-step plan.</li><li>Executors tackle each step, invoking tools as needed.</li><li>If something goes wrong, the system replans.</li></ol><h3><strong>Building a Simple Plan-and-Execute Agent</strong></h3><p>Here’s how you can build your own Plan-and-Execute agent using Python and LangGraph:</p><h4>Planner</h4><p>Initiate the planner and define the planning step</p><pre>planner_prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (<br>            &quot;system&quot;,<br>            &quot;&quot;&quot;For the given objective, come up with a simple step by step plan. \<br>This plan should involve individual tasks, that if executed correctly will yield the correct answer. Do not add any superfluous steps. \<br>The result of the final step should be the final answer. Make sure that each step has all the information needed - do not skip steps.&quot;&quot;&quot;,<br>        ),<br>        (&quot;placeholder&quot;, &quot;{messages}&quot;),<br>    ]<br>)<br>planner = planner_prompt | model.with_structured_output(Plan)<br><br><br>async def plan_step(state: PlanExecute):<br>    # Generates a comprehensive plan for the task<br>    plan = await planner.ainvoke({&quot;messages&quot;: [(&quot;user&quot;, state[&quot;input&quot;])]})<br>    return {&quot;plan&quot;: plan.steps}</pre><p>This snippet shows how we start: by creating a detailed plan before taking any action.</p><h4>Executor</h4><p>The real magic happens in how we execute that plan. Proper use of tools can give great results here.</p><pre>async def execute_step(state: PlanExecute):<br>    plan = state[&quot;plan&quot;]<br>    # Formatting the plan for clear execution<br>    plan_str = &quot;\n&quot;.join(f&quot;{i+1}. {step}&quot; for i, step in enumerate(plan))<br>    task = plan[0]<br>    <br>    # Invoke the agent with a clear, context-rich prompt<br>    agent_response = await agent_executor.ainvoke(<br>        {&quot;messages&quot;: [(&quot;user&quot;, f&quot;&quot;&quot;For the following plan:<br>{plan_str}\n\nYou are tasked with executing step {1}, {task}.&quot;&quot;&quot;)]}<br>    )<br>    <br>    return {<br>        &quot;past_steps&quot;: [(task, agent_response[&quot;messages&quot;][-1].content)],<br>    }</pre><h4>The Replanning Mechanism</h4><p>But what if the initial plan doesn’t work? That’s where our replanning comes in:</p><pre>class Response(BaseModel):<br>    &quot;&quot;&quot;Response to user.&quot;&quot;&quot;<br><br>    response: str<br><br><br>class Act(BaseModel):<br>    &quot;&quot;&quot;Action to perform.&quot;&quot;&quot;<br><br>    action: Union[Response, Plan] = Field(<br>        description=&quot;Action to perform. If you want to respond to user, use Response. &quot;<br>        &quot;If you need to further use tools to get the answer, use Plan.&quot;<br>    )<br><br><br>replanner_prompt = ChatPromptTemplate.from_template(<br>    &quot;&quot;&quot;For the given objective, come up with a simple step by step plan. \<br>This plan should involve individual tasks, that if executed correctly will yield the correct answer. Do not add any superfluous steps. \<br>The result of the final step should be the final answer. Make sure that each step has all the information needed - do not skip steps.<br><br>Your objective was this:<br>{input}<br><br>Your original plan was this:<br>{plan}<br><br>You have currently done the follow steps:<br>{past_steps}<br><br>Update your plan accordingly. If no more steps are needed and you can return to the user, then respond with that. Otherwise, fill out the plan. Only add steps to the plan that still NEED to be done. Do not return previously done steps as part of the plan.&quot;&quot;&quot;<br>)<br><br><br>replanner = replanner_prompt | model.with_structured_output(Act)<br><br>async def replan_step(state: PlanExecute):<br>    output = await replanner.ainvoke(state)<br>    if isinstance(output.action, Response):<br>        return {&quot;response&quot;: output.action.response}<br>    else:<br>        return {&quot;plan&quot;: output.action.steps}</pre><h4>Putting It All Together</h4><p>Creating graph nodes in LangGraph</p><pre>async def execute_step(state: PlanExecute):<br>    plan = state[&quot;plan&quot;]<br>    plan_str = &quot;\n&quot;.join(f&quot;{i+1}. {step}&quot; for i, step in enumerate(plan))<br>    task = plan[0]<br>    task_formatted = f&quot;&quot;&quot;For the following plan:<br>{plan_str}\n\nYou are tasked with executing step {1}, {task}.&quot;&quot;&quot;<br>    agent_response = await agent_executor.ainvoke(<br>        {&quot;messages&quot;: [(&quot;user&quot;, task_formatted)]}<br>    )<br>    return {<br>        &quot;past_steps&quot;: [(task, agent_response[&quot;messages&quot;][-1].content)],<br>    }<br><br><br>async def plan_step(state: PlanExecute):<br>    plan = await planner.ainvoke({&quot;messages&quot;: [(&quot;user&quot;, state[&quot;input&quot;])]})<br>    return {&quot;plan&quot;: plan.steps}<br><br><br>async def replan_step(state: PlanExecute):<br>    output = await replanner.ainvoke(state)<br>    if isinstance(output.action, Response):<br>        return {&quot;response&quot;: output.action.response}<br>    else:<br>        return {&quot;plan&quot;: output.action.steps}<br><br><br>def should_end(state: PlanExecute):<br>    if &quot;response&quot; in state and state[&quot;response&quot;]:<br>        return END<br>    else:<br>        return &quot;agent&quot;</pre><p>Making a graph in LangGraph</p><pre>workflow = StateGraph(PlanExecute)<br>workflow.add_node(&quot;planner&quot;, plan_step)<br>workflow.add_node(&quot;agent&quot;, execute_step)<br>workflow.add_node(&quot;replan&quot;, replan_step)<br><br>workflow.add_edge(START, &quot;planner&quot;)<br>workflow.add_edge(&quot;planner&quot;, &quot;agent&quot;)<br>workflow.add_edge(&quot;agent&quot;, &quot;replan&quot;)<br>workflow.add_conditional_edges(<br>    &quot;replan&quot;,<br>    should_end,<br>    [&quot;agent&quot;, END],<br>)<br><br># Compile the workflow<br>app = workflow.compile()</pre><p>This is how our graph looks like finally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*xe2PnjBao8NYX6b0D20CSQ.png" /><figcaption>This is how graph representation of our plan and execute agent looks like! Cool, isn’t it!!</figcaption></figure><h4>Why This Matters</h4><p>Traditional AI agents were like rigid robots following a script. Our new approach? It’s more like a flexible strategist:</p><ul><li>Creates comprehensive plans upfront</li><li>Adapts when things don’t go as expected</li><li>Maintains context across task execution</li><li>Reduces computational overhead</li></ul><h4>Real-World Applications</h4><p>Imagine deploying this for:</p><ul><li>Complex research tasks</li><li>Multi-step problem-solving</li><li>Dynamic customer support scenarios</li><li>Adaptive project management</li></ul><h4>The Road Ahead</h4><p>We’re just scratching the surface. The future of AI agents lies in architectures that can plan, execute, learn, and adapt — almost like having a super-intelligent assistant that truly understands context.</p><h4>Final Thoughts</h4><p>The Plan-and-Execute paradigm isn’t just an incremental improvement. It’s a fundamental reimagining of how AI agents can tackle complex tasks. We’re moving from reactive systems to proactive, strategic problem-solvers.</p><h4><strong>Inspired by:</strong></h4><ul><li>Wang et al.’s Plan-and-Solve Prompting Research</li><li>Yohei Nakajima’s Groundbreaking BabyAGI Project</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6c60b5b9598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Contextual Embeddings to Trillion Parameters: A Timeline of Key Milestones in NLP Models]]></title>
            <link>https://medium.com/@shubham.ksingh.cer14/from-contextual-embeddings-to-trillion-parameters-a-timeline-of-key-milestones-in-nlp-models-e4ff454585cb?source=rss-78f678a92dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4ff454585cb</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[clip]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[t5]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shubham Kumar Singh]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 20:05:06 GMT</pubDate>
            <atom:updated>2024-09-24T20:05:06.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiNhPvwbYCw1hz5-CkmJkA.jpeg" /></figure><p>While exploring T5, I became curious about the concept of multiple downstream tasks, which we often take for granted thanks to models like GPT-3. To gain a better understanding, I delved into the timeline of significant NLP research papers. This journey, along with other prompts, led me to valuable insights that I’m sharing here for future reference (and hopefully for others as well).</p><p>This article highlights key papers and milestones in the field of Natural Language Processing. <em>A large portion of this content was generated by ChatGPT.</em></p><p>Okay, we will first look at the BIG names:</p><p>Here’s a timeline of the key models, along with the pivotal moment when we started using one model for multiple downstream tasks:</p><p><strong>1. GPT-1 (2018)</strong></p><ul><li><strong>Paper:</strong> <em>Improving Language Understanding by Generative Pre-Training</em></li><li><strong>Publisher:</strong> OpenAI</li><li><strong>Key Contribution:</strong> GPT-1 introduced the concept of pre-training a transformer model on a large corpus using an unsupervised language modeling objective (predicting the next word) and then fine-tuning it on specific tasks. This was one of the first notable examples of <strong>transfer learning</strong> in NLP, allowing a single pre-trained model to be fine-tuned for multiple tasks.</li><li><strong>Architecture:</strong> Transformer-based (decoder-only).</li><li><strong>Impact:</strong> It demonstrated that a model pre-trained on language data can be fine-tuned for specific downstream tasks, like sentiment analysis or text classification, with strong performance.</li></ul><p><strong>2. BERT (October 2018)</strong></p><ul><li><strong>Paper:</strong> <em>BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</em></li><li><strong>Publisher:</strong> Google AI</li><li><strong>Key Contribution:</strong> BERT (Bidirectional Encoder Representations from Transformers) shifted the paradigm by using a <strong>bidirectional transformer encoder</strong>. It was trained with a masked language model (MLM) objective, meaning that it predicts missing words in a sentence, thus learning a richer context.</li><li><strong>Architecture:</strong> Transformer-based (encoder-only).</li><li><strong>Impact:</strong> BERT revolutionized NLP by introducing <strong>one model for multiple downstream tasks</strong> via transfer learning. After pre-training, BERT could be fine-tuned for various tasks (like question answering, sentence classification, named entity recognition, etc.), achieving state-of-the-art results. This was a crucial moment where one pre-trained model could be adapted to a wide range of tasks, which was further amplified by its performance on benchmarks like GLUE.</li></ul><p><strong>3. GPT-2 (February 2019)</strong></p><ul><li><strong>Paper:</strong> <em>Language Models are Unsupervised Multitask Learners</em></li><li><strong>Publisher:</strong> OpenAI</li><li><strong>Key Contribution:</strong> GPT-2 scaled up GPT-1 significantly (with up to 1.5 billion parameters) and demonstrated that language models pre-trained in a generative fashion could exhibit <strong>zero-shot learning</strong> capabilities. Without any task-specific fine-tuning, GPT-2 was able to perform reasonably well on several tasks by just seeing a task prompt.</li><li><strong>Architecture:</strong> Transformer-based (decoder-only).</li><li><strong>Impact:</strong> GPT-2 showed that one generative model could be used for a broad range of downstream tasks, even without fine-tuning (through prompts), marking a step toward universal models for many tasks.</li></ul><p><strong>4. T5 (October 2019)</strong></p><ul><li><strong>Paper:</strong> <em>Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer</em></li><li><strong>Publisher:</strong> Google Research</li><li><strong>Key Contribution:</strong> T5 (Text-To-Text Transfer Transformer) unified all NLP tasks into a single text-to-text framework. Every problem, including classification, translation, summarization, etc., was framed as a text generation task.</li><li><strong>Architecture:</strong> Transformer-based (encoder-decoder).</li><li><strong>Impact:</strong> T5 made <strong>task unification</strong> explicit by converting every NLP task into a text-to-text problem. This reinforced the idea of using a single model and architecture for multiple downstream tasks by leveraging transfer learning, but now with a standardized format (text input → text output).</li></ul><p><strong>5. GPT-3 (June 2020)</strong></p><ul><li><strong>Paper:</strong> <em>Language Models are Few-Shot Learners</em></li><li><strong>Publisher:</strong> OpenAI</li><li><strong>Key Contribution:</strong> GPT-3 massively scaled up the GPT-2 architecture to 175 billion parameters and demonstrated <strong>few-shot, one-shot, and zero-shot learning</strong> capabilities. This model required little or no task-specific fine-tuning but could handle a wide range of tasks purely through prompting.</li><li><strong>Architecture:</strong> Transformer-based (decoder-only).</li><li><strong>Impact:</strong> GPT-3 marked the point where one large, pre-trained model could handle a wide variety of downstream tasks without fine-tuning, purely by changing the task prompt. This was a major leap in the generality of language models.</li></ul><p><strong>Moment of Transition to One Model for Multiple Tasks:</strong></p><ul><li><strong>BERT (2018)</strong> was the <strong>key turning point</strong> for transfer learning in NLP, where a single pre-trained model could be fine-tuned for many downstream tasks, achieving strong results across the board. This was the start of using one model for multiple downstream tasks with task-specific fine-tuning.</li><li><strong>GPT-2 (2019)</strong> and <strong>GPT-3 (2020)</strong> took this further, demonstrating that a generative pre-trained model could also handle multiple tasks, but with fewer or no fine-tuning steps by simply using prompts (especially in GPT-3’s case).</li></ul><p>Overall, BERT, GPT-2, and GPT-3 collectively pushed NLP towards the paradigm where one large pre-trained model could be adapted to numerous tasks, with increasing capabilities for few-shot and zero-shot learning.</p><h4>Other important papers and models which can’t be missed:</h4><p>that helped shape the landscape of NLP and <strong>transfer learning</strong>. Here’s a list of additional pivotal models you might want to consider:</p><p><strong>1. ELMo (February 2018)</strong></p><ul><li><strong>Paper:</strong> <em>Deep Contextualized Word Representations</em></li><li><strong>Publisher:</strong> AllenNLP</li><li><strong>Key Contribution:</strong> ELMo (Embeddings from Language Models) introduced deep contextualized word embeddings. Unlike static embeddings like word2vec or GloVe, ELMo generated word representations that change depending on the context in which a word is used.</li><li><strong>Architecture:</strong> Bidirectional LSTM.</li><li><strong>Impact:</strong> ELMo demonstrated that contextualized word embeddings significantly improved the performance of models on many NLP tasks. It preceded BERT and showed the value of dynamic, context-dependent word representations.</li></ul><p><strong>2. ULLa (November 2019)</strong></p><ul><li><strong>Paper:</strong> <em>Unsupervised Cross-lingual Representation Learning at Scale</em></li><li><strong>Publisher:</strong> Facebook AI (Meta AI)</li><li><strong>Key Contribution:</strong> ULLa explored cross-lingual transfer learning in an unsupervised manner. It used a multilingual transformer and trained on massive amounts of text in different languages, enabling cross-lingual applications.</li><li><strong>Architecture:</strong> Transformer-based.</li><li><strong>Impact:</strong> ULLa showed that multilingual transformers could outperform task-specific translation models and was a key model in the multilingual transfer learning space.</li></ul><p><strong>3. XLNet (June 2019)</strong></p><ul><li><strong>Paper:</strong> <em>XLNet: Generalized Autoregressive Pretraining for Language Understanding</em></li><li><strong>Publisher:</strong> Google Research and Carnegie Mellon University</li><li><strong>Key Contribution:</strong> XLNet combined the advantages of autoregressive models like GPT and autoencoding models like BERT. It introduced a new permutation-based training objective that allowed it to model bidirectional context without masking.</li><li><strong>Architecture:</strong> Transformer-based (autoregressive with permutation-based training).</li><li><strong>Impact:</strong> XLNet outperformed BERT on many NLP benchmarks, furthering the shift toward large pre-trained models for downstream tasks. Its training methodology is still considered significant for sequence generation tasks.</li></ul><p><strong>4. RoBERTa (July 2019)</strong></p><ul><li><strong>Paper:</strong> <em>RoBERTa: A Robustly Optimized BERT Pretraining Approach</em></li><li><strong>Publisher:</strong> Facebook AI</li><li><strong>Key Contribution:</strong> RoBERTa (A Robustly Optimized BERT) built on BERT’s architecture but optimized the pre-training procedure. It showed that BERT was under-trained and improved performance by training longer with larger batches, a larger learning rate, and more data.</li><li><strong>Architecture:</strong> Transformer-based (encoder-only, like BERT).</li><li><strong>Impact:</strong> RoBERTa demonstrated that architectural changes weren’t always needed to improve model performance — training methods and data quality could also significantly boost outcomes. RoBERTa became a popular choice for many NLP tasks.</li></ul><p><strong>5. ALBERT (September 2019)</strong></p><ul><li><strong>Paper:</strong> <em>ALBERT: A Lite BERT for Self-supervised Learning of Language Representations</em></li><li><strong>Publisher:</strong> Google Research</li><li><strong>Key Contribution:</strong> ALBERT reduced the memory and computation required by BERT, making large models more efficient. It did so by parameter-sharing across layers and factorizing the embedding parameters.</li><li><strong>Architecture:</strong> Transformer-based (encoder-only, like BERT).</li><li><strong>Impact:</strong> ALBERT achieved performance similar to BERT while being more resource-efficient, enabling the use of large models on smaller hardware.</li></ul><p><strong>6. Switch Transformer (January 2021)</strong></p><ul><li><strong>Paper:</strong> <em>Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity</em></li><li><strong>Publisher:</strong> Google Research</li><li><strong>Key Contribution:</strong> This model used a <strong>mixture of experts</strong> (MoE) approach, where only a subset of parameters (or “experts”) is activated at a time. This allowed the model to scale to trillions of parameters without a linear increase in computational cost.</li><li><strong>Architecture:</strong> Transformer-based (MoE for parameter-efficient scaling).</li><li><strong>Impact:</strong> Switch Transformers introduced a novel scaling method, pushing the boundaries of model size in an efficient way. It furthered the trend toward larger and more generalizable models while maintaining training efficiency.</li></ul><p><strong>7. CLIP (January 2021)</strong></p><ul><li><strong>Paper:</strong> <em>Learning Transferable Visual Models From Natural Language Supervision</em></li><li><strong>Publisher:</strong> OpenAI</li><li><strong>Key Contribution:</strong> CLIP (Contrastive Language-Image Pretraining) introduced a <strong>multimodal model</strong> that learned joint representations for images and text, significantly improving transfer learning for tasks involving both modalities.</li><li><strong>Architecture:</strong> Transformer-based (vision and language).</li><li><strong>Impact:</strong> CLIP showed that models could be pre-trained on large-scale image-text pairs and perform competitively on image classification tasks, without any task-specific data fine-tuning. It was a milestone in <strong>multimodal learning</strong> and demonstrated the power of <strong>self-supervised learning</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4ff454585cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Attention in Transformers, with code.]]></title>
            <link>https://medium.com/@shubham.ksingh.cer14/understanding-attention-in-transformers-with-code-1ddd6c07abf4?source=rss-78f678a92dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ddd6c07abf4</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shubham Kumar Singh]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 18:13:31 GMT</pubDate>
            <atom:updated>2024-09-09T18:40:31.089Z</atom:updated>
            <content:encoded><![CDATA[<p>The attention layer is one of the core components of the Transformer model. It takes in a set of input words (technically called tokens, which can be words or subwords) and outputs new, contextually aware embeddings for each word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSLFipjgF4ABaSbAKuV_Jw.png" /></figure><p>One of the most crucial properties of the attention layer is <strong>parallelism</strong>, which enables the model to process all tokens in a sequence simultaneously. Unlike RNNs, which process tokens one at a time, the Transformer’s attention mechanism operates over the entire sequence in parallel, making it highly efficient and scalable — this is what makes Transformers the <strong>GOAT</strong> for sequence modeling tasks.</p><p>From a high-level perspective, two major things happen inside the attention layer:</p><ol><li>First, it calculates how each token in a sequence should “attend” to the others, determining which tokens are most relevant to one another.</li><li>Then, the layer uses this information to adjust or “refine” the token embeddings, enhancing them with information from other tokens based on their relevance.</li></ol><p>In essence, attention helps the model figure out which tokens should focus on which other tokens. Once the attention pattern is established — a matrix of weights showing these relationships — it is applied to refine the original embeddings. The result is a set of updated embeddings that better capture the relationships between the tokens in the input sequence.</p><p>In this blog we will look at both functions of the attention layer in somewhat detail. We will understand them first and then implement</p><p>In the Transformer architecture, attention mechanisms are used in both the encoder and the decoder. But what exactly does attention do?</p><h3>Intuition</h3><p>The following image and excerpt from Lillian’s <a href="https://lilianweng.github.io/posts/2018-06-24-attention/">blog</a> helps build intution for attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UO3F9vjhTla43xn-WK11RQ.png" /></figure><p>The content of the 3 red boxes, eyes, ears and nose of a dog, provides clues about what to expect in that yellow box. We expect to see an ear. So given a small patch of the image, pixels in the rest provides clues on what should be displayed there.</p><p>However, the sweater and blanket at the bottom would not be as helpful as those doggy features.</p><p>Similar argument goes for words in one sentence or close context.</p><p>When predicting the next word in a sentence, not all of the preceding words are equally useful. Some words provide strong clues, while others contribute less. Let’s look at an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cfBtbxWsdo9Wo5la6JtaAA.png" /></figure><p>Consider the word “eating.” It suggests that a food-related word is likely to follow. In contrast, words like “She” and “is” offer little insight into what the next word might be. Attention tries to capture this relationship amongst words.</p><p>Jay Alammar has used the following example in <a href="https://jalammar.github.io/illustrated-transformer/">his blog</a> (highly recommended)</p><blockquote>Say the following sentence is an input sentence we want to translate:</blockquote><blockquote>”The animal didn&#39;t cross the street because it was too tired”</blockquote><blockquote>What does “it” in this sentence refer to? Is it referring to the street or to the animal? It’s a simple question to a human, but not as simple to an algorithm.</blockquote><blockquote>When the model is processing the word “it”, self-attention allows it to associate “it” with “animal”.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*s1I3mXPOfV_waMMkWpWuiQ.png" /></figure><p>More examples of Attention from the “Attention is all you need” paper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MEQXaxJihVo5MzY7lWI3Lg.png" /></figure><p>Understanding of phrase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9uMsDKMi5BMeyc6V2QDYtw.png" /></figure><p>Let’s try to formulate this notion a bit more mathematically. To quantify attention, the authors of the paper introduced three vectors — Q (Query), K (Key), and V (Value) — for each input token. Every token has its own set of these vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abmWOcJmVAzDEwxtls5TXQ.png" /></figure><p>The matrices Wq, Wk, and Wv are learned parameters within the attention layers. By multiplying the input tokens by these matrices, we obtain their corresponding Q, K, and V vectors.</p><p>You can think of them like this:</p><p>• Q: What am I looking for?<br> • K: What information do I have?<br> • V: What will I communicate?</p><h4>Attention Scores</h4><p>Let’s focus on the first token. Our goal is to determine which other tokens have the information that this token is looking for. Specifically, we want to find the tokens whose K vectors are most similar to the Q vector of the first token. To do this, we compute the dot product between the Q vector of the first token and the K vectors of all other tokens. The dot product serves as a good measure of similarity between vectors — the more similar the vectors, the higher the dot product.</p><p>These dot products are referred to as <strong>attention scores</strong>, which dictate how much focus should be placed on other parts of the input sentence while encoding a token at a specific position.</p><p>We calculate these scores for every token against every other token, forming a matrix with dimensions <strong>sentence_length x sentence_length</strong>. This matrix is known as the <strong>attention pattern</strong>.</p><p>Let’s look at a few attention patterns produced by transformers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tylHI3gnaRnkVk9DKct9rw.png" /></figure><p>Out of all these examples, I found (a) most interesting. Have a closer look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LV6vjdHDuBEHo-Sg2F0gYA.png" /></figure><p>This is how the paper “Attention is all you need” defines attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyypDNrIOZYw2GhVpDDIog.png" /></figure><p>Attention is calculated for every token in a sequence simultaneously, using the same parameters for each token.</p><h4>Refining Embeddings using Attention</h4><blockquote>We use attention to enable flow of information across word embeddings which in turn helps us refine them.</blockquote><p>The initial embedding for each word is some high dimensional vector which only encodes the meaning of only that particular word with no context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wofO6o1PSXRi3pcksDCrzQ.png" /><figcaption>Source: <a href="https://youtu.be/eMlx5fFNoYc?si=kgb6LUTD7yndY-9p">this</a> video. I highly recommend this video. This is one of my favourite channels on youtube</figcaption></figure><p>The goal is to perform a series of computations to produce a new set of embeddings where each embedding has absorbed meaning from the other relevant embeddings. For example, nouns might take on meaning from adjectives, and pronouns might draw meaning from their corresponding nouns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JowstTbUphxA-IwMeXnHkA.png" /></figure><p>Attention is the mechanism that guides how much meaning each word in a sequence absorbs from other words, helping to update each embedding with relevant information.</p><ol><li>We will use the scores in attention patterns as weights</li><li>And take a weighted average</li></ol><h3>3 types of attention in original transformer</h3><ol><li>Self attention in encoder blocks.</li><li>Masked self attention in decoder blocks</li><li>Cross attention/Encoder-decoder attention the decoder block.</li></ol><h4>Cross Attention</h4><p>In cross-attention, the Key (K) and Value (V) matrices are derived from the encoder output, while the Query (Q) matrix comes from the previous decoder’s output (or target embeddings in first decoder):</p><ul><li><strong>K and V derived from Encoder’s Output:</strong> The K and V matrices are derived from the output of the last encoder block. Specifically, we take the output of the final encoder in the encoder stack and pass it to every decoder block. Each decoder block then creates its own K and V values by applying linear projections to this encoder output.</li><li><strong>Q derived from Decoder:</strong> The Q matrix comes from the decoder’s previous state. This can either be the output from the previous decoder block or the previously predicted token if we are at the first decoder block. Once we have Q, K and V, rest of the process is same as self attention.</li></ul><p>In short, cross-attention enables the decoder to focus on different parts of the input sequence (via K and V) depending on what it has generated so far (via Q). This mechanism ensures that the model effectively leverages the information from the source sentence to inform its predictions in the target sentence.</p><h4>Multi-head Attention</h4><p>We split the generated Q, K and V into h parts of d_k length each. Then attention computations are done for each part in parallel. These parallel layers are called heads. The output of these heads i.e Value vectors are concatenated to get V vector of length d_model. Then this is passed to the next layer.</p><h3>Implementing Attention Layer in Pytorch</h3><ol><li><strong>Compute Q, K, and V:</strong> For each word or token in the sequence, we compute the Query (Q), Key (K), and Value (V) vectors by linearly projecting x or y.</li><li><strong>Split/Project Q, K, and V into smaller pieces</strong>: These vectors are split or into <em>h</em> smaller pieces (heads), each of length <strong><em>d_k</em></strong>. Note that <strong>h * d_k = d_model, </strong>where d_model was the initial length of Q, K and V before the split. In the paper, h = 8, d_k = 64, d_model = 512.</li><li><strong>Calculate Attention Patterns:</strong> Using the projected Q, K, and V for different heads, we compute the attention pattern for each head. This pattern is then used to calculate new, refined values by taking the weighted average of the Value vectors, where the weights are determined by the attention pattern, typically computed as</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyypDNrIOZYw2GhVpDDIog.png" /></figure><pre>def scaled_dot_product_attention(query, key, value, mask=None):<br>    &quot;&quot;&quot;<br>    Compute the scaled dot-product attention.<br>    &quot;&quot;&quot;<br>    d_k = query.size(-1)  # Dimension of the key/query vectors<br>    # Compute the dot products<br>    scores = torch.matmul(query, key.transpose(-2, -1)) / d_k**0.5<br>    <br>    # Apply the mask (if provided)<br>    if mask is not None:<br>        scores = scores.masked_fill(mask == 0, float(&#39;-inf&#39;))<br>    <br>    # Compute the attention weights<br>    attention_weights = F.softmax(scores, dim=-1)<br>    <br>    # Apply dropout<br>    attention_weights = attention_weights.dropout(0.1)<br>    <br>    # Compute the weighted sum of the values<br>    output = torch.matmul(attention_weights, value)<br>    <br>    return output, attention_weights</pre><p>4. <strong>Concatenate Values:</strong> The Value matrices from all heads are concatenated to form a single matrix of length `d_model`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81vReU_GkNSHDQeFGjAJYg.png" /></figure><p>The naming convention in model is a little confusing. It can be updated like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*DE98L39ZecoYtj2kgp8B5A.png" /><figcaption>Source: <a href="https://ai.stackexchange.com/questions/39151/attention-is-all-you-need-paper-how-are-the-q-k-v-values-calculated#:~:text=Q%2C%20K%20and%20V%20values,2%20of%20the%20paper.&amp;text=In%20this%20new%20notation%2C%20X,to%20the%20current%20attention%20unit.">this stack overflow post</a></figcaption></figure><p>Similarly, Figure 2 of the paper could be modified accordingly :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*MMlWT6aB21o9AgbUmh7dfg.png" /><figcaption>In my opinion this naming convention makes more sense.</figcaption></figure><p>In this new notation, 𝑋 and 𝑌 are the inputs to the current attention unit.</p><ul><li>For self attention, we’d have 𝑋=𝑌 which would both be the previous en/decoder block output (or word embedding for the first encoder block).</li><li>For cross-attention, 𝑋 would be the output of the last encoder block and 𝑌 the output of the previous decoder block.</li></ul><p>5. <strong>Apply Final Linear Layer:</strong> Before passing the result to the feedforward layer, a final linear transformation is applied. This step is essential to scale the concatenated output back to the original d_model size. Although, if value matrices had size d_k, concatenation will already bring back the size to d_model.</p><p>— The linear layer is crucial to scale the output from h * d_v back to d_model. In the original implementation, h * d_v = d_model, the layer simply becomes a same-dimension transformation like nn.Linear(d_model, d_model). However, the layer adapts to nn.Linear(d_v * h, d_model), allowing the model to stay flexible and consistent across different values of d_v and h . It’s also worth noting that in many implementations, d_v is set equal to d_k , although this isn’t a strict requirement.</p><h4>Masked Self Attention</h4><p>Understanding the difference between the decoder’s behavior during inference and training is key to grasping why masking is needed.</p><p><strong>Inference vs. Training:</strong></p><ul><li><strong>During Inference:</strong> The decoder is given a partial sentence and is expected to predict the next word. For example, if the input is “The cat is,” the decoder needs to generate the word “sitting” without knowing the rest of the sentence.</li><li><strong>During Training:</strong> The decoder is provided with the entire sentence, and the goal is to train it to predict the next word for each part of the sentence. However, if the decoder could see the entire sentence during training, it would simply memorize the sequence, rather than learning how to predict the next word based on the given context.</li></ul><h4>Role of Masking:</h4><p>To simulate the conditions of inference during training, we use masking. Masking ensures that, while training, the decoder can only attend to the tokens up to the current position and not look ahead. This prevents the decoder from “cheating” by accessing future tokens, forcing it to learn how to generate the next word based only on the preceding context, just as it would during inference.</p><p>In essence, masking during training teaches the decoder to generate sequences in a step-by-step manner, which is crucial for making accurate predictions when the model is actually being used.</p><h4>Masking Intuition</h4><p>Consider the sentence “The FBI is chasing a criminal on the run.” During training, we have access to the entire sentence, and we perform computations for all tokens in parallel. However, to ensure that the decoder learns to predict each word based only on the preceding context, we need to carefully manage how information flows between tokens.</p><p>Let’s focus on the token “criminal.” When calculating the attention pattern for this token — essentially determining how “criminal” relates to the words that came before it — we need to ensure that the model doesn’t cheat by looking ahead at the tokens that follow “criminal.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gB170_3CqgCd-aJyi1Uglg.png" /><figcaption>The size/darkness of color represents attention level.</figcaption></figure><p>To achieve this, we apply a mask to the tokens that come after “criminal,” such as “on,” “the,” and “run.” By masking these future tokens, we ensure that they are not considered during the attention calculations for “criminal.” This forces the model to base its understanding of “criminal” only on the context provided by the preceding words (“The FBI is chasing a”), rather than the full sentence.</p><p>This masking process is crucial because it mirrors the conditions the model will face during inference, where it won’t have access to future tokens and must predict the next word based solely on what it has seen so far.</p><pre>def subsequent_mask(size):<br>    &quot;Mask out subsequent positions.&quot;<br>    attn_shape = (1, size, size)<br>    subsequent_mask = torch.triu(torch.ones(attn_shape), diagonal=1).type(<br>        torch.uint8<br>    )<br>    return subsequent_mask == 0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*0dA-2R3ZP03R2zYvSvoPzA.png" /></figure><p>For example, if the model is translating “The cat sat on the mat,” and it has already generated “Le chat s’est,” the cross-attention mechanism might use the Q matrix to focus on the word “sat” in the source sentence, helping the model generate the correct next word in French, such as “assis.” The Q matrix from the decoder guides this focus, ensuring that the model attends to the most relevant parts of the input sequence when making predictions.</p><h4>Implementing Attention in code</h4><p>I strongly believe that the way to improve your coding skill is to read other people’s (good) code. Let’s look at a few implementations of Attention.</p><p>Following is my implementation of multi-headed attention (with help from ChatGPT, ofcourse)</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class MultiHeadAttention(nn.Module):<br>    def __init__(self, d_model, num_heads, dropout=0.1):<br>        super(MultiHeadAttention, self).__init__()<br>        assert d_model % num_heads == 0<br>        <br>        self.num_heads = num_heads<br>        self.d_k = d_model // num_heads<br>        self.d_v = self.d_k<br><br>        # Linear projections<br>        self.linear_q = nn.Linear(d_model, self.d_k * num_heads)<br>        self.linear_k = nn.Linear(d_model, self.d_k * num_heads)<br>        self.linear_v = nn.Linear(d_model, self.d_v * num_heads)<br>        self.linear_out = nn.Linear(self.d_v * num_heads, d_model)<br><br>        self.dropout = nn.Dropout(dropout)<br><br>    def forward(self, query, key, value, mask=None):<br>        batch_size = query.size(0)<br>        <br>        # Linear projections<br>        Q = self.linear_q(query)<br>        K = self.linear_k(key)<br>        V = self.linear_v(value)<br>        <br>        # Split into multiple heads<br>        Q = Q.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)<br>        K = K.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)<br>        V = V.view(batch_size, -1, self.num_heads, self.d_v).transpose(1, 2)<br>        <br>        # Compute attention for each head<br>        output, attention_weights = scaled_dot_product_attention(Q, K, V, mask)<br>        <br>        # Concatenate heads<br>        output = output.transpose(1, 2).contiguous().view(batch_size, -1, self.d_v * self.num_heads)<br>        <br>        # Final linear layer<br>        output = self.linear_out(output)<br>        return output<br><br>def scaled_dot_product_attention(query, key, value, mask=None):<br>    &quot;&quot;&quot;<br>    Compute the scaled dot-product attention.<br>    &quot;&quot;&quot;<br>    d_k = query.size(-1)  # Dimension of the key/query vectors<br><br>    # Compute the dot products<br>    # scores = torch.matmul(query, key.transpose(-2, -1)) / d_k**0.5<br>    scores = torch.einsum(&#39;bhqd,bhkd-&gt;bhqk&#39;, query, key) / d_k ** 0.5<br>    <br>    # Apply the mask (if provided)<br>    if mask is not None:<br>        scores = scores.masked_fill(mask == 0, float(&#39;-inf&#39;))<br>    <br>    # Compute the attention weights<br>    attention_weights = F.softmax(scores, dim=-1)<br>    <br>    # Apply dropout<br>    attention_weights = attention_weights.dropout(0.1)<br>    <br>    # Compute the weighted sum of the values<br>    output = attention_weights @ value<br>    <br>    return output, attention_weights<br><br># Example usage<br>batch_size = 2<br>seq_len = 4<br>d_model = 512<br>num_heads = 8<br><br># Create the MultiHeadAttention layer<br>mha = MultiHeadAttention(d_model, num_heads)<br><br># Random input tensors<br>query = torch.randn(batch_size, seq_len, d_model)<br>key = torch.randn(batch_size, seq_len, d_model)<br>value = torch.randn(batch_size, seq_len, d_model)<br>mask = torch.ones(batch_size, 1, seq_len, seq_len)  # Optional mask, here it&#39;s all ones<br><br># Apply the multi-head attention<br>output = mha(query, key, value, mask)<br><br>print(&quot;Output shape:&quot;, output.shape)  # Should be (batch_size, seq_len, d_model)</pre><p>In this above code block, following line seems very unintuitive, let me explain it a little bit</p><pre>Q = Q.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)<br> <br>&#39;&#39;&#39;<br>A note on dimension conversions in the above code block<br> 1. view(batch_size, -1, self.num_heads, self.d_k) -&gt; splits the d_model dimension into self.num_heads heads, where each head has a dimension of self.d_k <br>     So, the shape after view becomes -&gt; (batch_size, sequence_length, self.num_heads, self.d_k)<br> 2. transpose(1, 2)  -&gt; This operation swaps the sequence_length and num_heads dimensions.<br>        After the transpose, the new shape becomes -&gt; (batch_size, self.num_heads, sequence_length, self.d_k)<br><br>Why transpose?        <br>By moving self.num_heads to the second dimension, the model can now treat each <br>head independently during the attention calculation. This allows the attention <br>mechanism to be computed for all heads in parallel within a batch, rather than <br>sequentially across heads.<br>&#39;&#39;&#39;</pre><p>Another simpler implementation from <a href="https://github.com/hyunwoongko/transformer">here</a></p><pre>class MultiHeadAttention(nn.Module):<br><br>    def __init__(self, d_model, n_head):<br>        super(MultiHeadAttention, self).__init__()<br>        self.n_head = n_head<br>        self.attention = ScaleDotProductAttention()<br>        self.w_q = nn.Linear(d_model, d_model)<br>        self.w_k = nn.Linear(d_model, d_model)<br>        self.w_v = nn.Linear(d_model, d_model)<br>        self.w_concat = nn.Linear(d_model, d_model)<br><br>    def forward(self, q, k, v, mask=None):<br>        # 1. dot product with weight matrices<br>        q, k, v = self.w_q(q), self.w_k(k), self.w_v(v)<br><br>        # 2. split tensor by number of heads<br>        q, k, v = self.split(q), self.split(k), self.split(v)<br><br>        # 3. do scale dot product to compute similarity<br>        out, attention = self.attention(q, k, v, mask=mask)<br>        <br>        # 4. concat and pass to linear layer<br>        out = self.concat(out)<br>        out = self.w_concat(out)<br><br>        # 5. visualize attention map<br>        # TODO : we should implement visualization<br><br>        return out<br><br>    def split(self, tensor):<br>        &quot;&quot;&quot;<br>        split tensor by number of head<br><br>        :param tensor: [batch_size, length, d_model]<br>        :return: [batch_size, head, length, d_tensor]<br>        &quot;&quot;&quot;<br>        batch_size, length, d_model = tensor.size()<br><br>        d_tensor = d_model // self.n_head<br>        tensor = tensor.view(batch_size, length, self.n_head, d_tensor).transpose(1, 2)<br>        # it is similar with group convolution (split by number of heads)<br><br>        return tensor<br><br>    def concat(self, tensor):<br>        &quot;&quot;&quot;<br>        inverse function of self.split(tensor : torch.Tensor)<br><br>        :param tensor: [batch_size, head, length, d_tensor]<br>        :return: [batch_size, length, d_model]<br>        &quot;&quot;&quot;<br>        batch_size, head, length, d_tensor = tensor.size()<br>        d_model = head * d_tensor<br><br>        tensor = tensor.transpose(1, 2).contiguous().view(batch_size, length, d_model)<br>        return tensor</pre><pre>class ScaleDotProductAttention(nn.Module):<br>    &quot;&quot;&quot;<br>    compute scale dot product attention<br><br>    Query : given sentence that we focused on (decoder)<br>    Key : every sentence to check relationship with Qeury(encoder)<br>    Value : every sentence same with Key (encoder)<br>    &quot;&quot;&quot;<br><br>    def __init__(self):<br>        super(ScaleDotProductAttention, self).__init__()<br>        self.softmax = nn.Softmax(dim=-1)<br><br>    def forward(self, q, k, v, mask=None, e=1e-12):<br>        # input is 4 dimension tensor<br>        # [batch_size, head, length, d_tensor]<br>        batch_size, head, length, d_tensor = k.size()<br><br>        # 1. dot product Query with Key^T to compute similarity<br>        k_t = k.transpose(2, 3)  # transpose<br>        score = (q @ k_t) / math.sqrt(d_tensor)  # scaled dot product<br><br>        # 2. apply masking (opt)<br>        if mask is not None:<br>            score = score.masked_fill(mask == 0, -10000)<br><br>        # 3. pass them softmax to make [0, 1] range<br>        score = self.softmax(score)<br><br>        # 4. multiply with Value<br>        v = score @ v<br><br>        return v, score</pre><p>The implementation from “The Annotated Transformer” is also noteworthy. Do check it out. Adding a snippet here.</p><pre>class MultiHeadedAttention(nn.Module):<br>    def __init__(self, h, d_model, dropout=0.1):<br>        &quot;Take in model size and number of heads.&quot;<br>        super(MultiHeadedAttention, self).__init__()<br>        assert d_model % h == 0<br>        # We assume d_v always equals d_k<br>        self.d_k = d_model // h<br>        self.h = h<br>        self.linears = clones(nn.Linear(d_model, d_model), 4)<br>        self.attn = None<br>        self.dropout = nn.Dropout(p=dropout)<br><br>    def forward(self, query, key, value, mask=None):<br>        &quot;Implements Figure 2&quot;<br>        if mask is not None:<br>            # Same mask applied to all h heads.<br>            mask = mask.unsqueeze(1)<br>        nbatches = query.size(0)<br><br>        # 1) Do all the linear projections in batch from d_model =&gt; h x d_k<br>        query, key, value = [<br>            lin(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)<br>            for lin, x in zip(self.linears, (query, key, value))<br>        ]<br><br>        # 2) Apply attention on all the projected vectors in batch.<br>        x, self.attn = attention(<br>            query, key, value, mask=mask, dropout=self.dropout<br>        )<br><br>        # 3) &quot;Concat&quot; using a view and apply a final linear.<br>        x = (<br>            x.transpose(1, 2)<br>            .contiguous()<br>            .view(nbatches, -1, self.h * self.d_k)<br>        )<br>        del query<br>        del key<br>        del value<br>        return self.linears[-1](x)</pre><p>It accomplishes the same task but looks overly complicated to me. Personally, I prioritise readability over brevity, as it makes debugging easier. However, everyone has their own preferences. 😊</p><p>This concludes our crash course in attention. From understanding what is attention to implementing it in Pytorch we have come a long way.</p><blockquote>At last I would like to thanks various decoder-only transformers (in LLMs) for grammar corrections and rewriting various parts of this post about their encoder-decoder friends. :P</blockquote><h4>References:</h4><p>I strongly recommend you go through all of them.</p><ol><li><a href="https://lilianweng.github.io/posts/2018-06-24-attention/">https://lilianweng.github.io/posts/2018-06-24-attention/</a></li><li><a href="https://nlp.seas.harvard.edu/annotated-transformer/#model-architecture">https://nlp.seas.harvard.edu/annotated-transformer/#model-architecture</a></li><li><a href="https://jalammar.github.io/illustrated-transformer/">https://jalammar.github.io/illustrated-transformer/</a></li><li><a href="https://github.com/gordicaleksa/pytorch-original-transformer/blob/main/models/definitions/transformer_model.py">https://github.com/gordicaleksa/pytorch-original-transformer/blob/main/models/definitions/transformer_model.py</a></li><li><a href="https://www.datacamp.com/tutorial/building-a-transformer-with-py-torch">https://www.datacamp.com/tutorial/building-a-transformer-with-py-torch</a></li><li><a href="https://youtu.be/eMlx5fFNoYc?si=bSzwSasVDdX3vYwR">https://youtu.be/eMlx5fFNoYc?si=bSzwSasVDdX3vYwR</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ddd6c07abf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diffusion Models from Scratch in PyTorch]]></title>
            <link>https://medium.com/@shubham.ksingh.cer14/diffusion-models-from-scratch-in-pytorch-cb6d349c14be?source=rss-78f678a92dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb6d349c14be</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[paper-implementation]]></category>
            <category><![CDATA[unet]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <dc:creator><![CDATA[Shubham Kumar Singh]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 12:05:04 GMT</pubDate>
            <atom:updated>2024-10-07T13:10:39.727Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Disclaimer:</strong> This blog focuses on building intuition for how diffusion models work (based on DDPM paper), highlighting only the important math needed for implementation. For a more detailed, math-heavy explanation, check out <a href="https://lilianweng.github.io/posts/2021-07-11-diffusion-models/">this</a> post by Lillian Weng of OpenAI.</p><p>Check out <a href="https://github.com/bumSin/DDPM-diffusion-pytorch">this repo</a> of mine for pytorch implementation of DDPM paper.</p><h3>Table of contents</h3><ol><li>What are diffusion models?</li><li>Forward Diffusion process<br>- Formula Intuition<br>- Another perspective<br>- The nice property<br>- Forward process implementation</li><li>Reverse Diffusion process<br>- Sampling Process</li><li>Loss Function/Objective function</li><li>Training Process</li><li>The neural network<br>- Block Class<br>- Resnet Block Class<br>- Time embeddings<br>- The U-Net Class</li><li>Conclusion</li><li>Some good resources</li></ol><p><em>Diffusion models like Stable Diffusion, DALL-E 2, and Google’s ImageGen have revolutionized image creation, all powered by Denoising Diffusion Probabilistic Models (DDPMs). In this blog, I’ll break down DDPMs step by step, covering the theory in simple terms and guiding you through implementation. By the end, you’ll understand DDPMs and have built your own model capable of generating new images. Corresponding </em><a href="https://github.com/bumSin/DDPM-diffusion-pytorch"><em>code repo</em></a><em>.</em></p><h3>What are Diffusion Models?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9qfCTCrk9rQV6rBWH_9ZA.png" /><figcaption>Gradually adding some noise to image</figcaption></figure><blockquote>Diffusion models are inspired by non-equilibrium thermodynamics. They define a (Markov) chain of diffusion steps to slowly add random noise to data and then learn to reverse the diffusion process to construct desired data samples from the noise.</blockquote><p>DDPMs (Denoising Diffusion Probabilistic Models) are a type of generative model designed to take noise (resembling TV static) as input and transform it into a realistic-looking image.</p><p>Interestingly, DDPMs aren’t trained directly to generate images. Instead, they learn to gradually remove noise from a noisy image. Once the model learns to de-noise, it is used to generate new images. We can produce realistic images by feeding the model pure noise and instructing it to de-noise repeatedly over several hundred steps.</p><p>Adding noise to images to produce noisy images for model training is called the <strong>Forward Diffusion process</strong></p><p>While on the other hand gradually denoising an image to produce a novel image is called the <strong>Reverse Diffusion process</strong></p><ol><li><strong>The Forward Diffusion process </strong>is fixed and can be formulated mathematically.</li><li><strong>The Reverse Diffusion process</strong> can’t be formulated mathematically and must be estimated by a model.</li></ol><h4><strong>Forward Diffusion process</strong></h4><p>To build a model that can predict the amount of noise in a given noisy image, we need to train it using pairs of noisy images and corresponding noise tensors. Moreover, the dataset should have images with varying amounts of noise, some images should have very less noise, while others might have too much noise and everything in between.</p><p>Enter the forward diffusion process.</p><p>Forward diffusion is a process that gradually transforms a clean, realistic image into pure Gaussian noise over a finite number of steps, denoted by T. In the DDPM paper, T is set to 1000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JswxkJolsBADyXiqH_LIGA.png" /><figcaption>Code to play around with this can be found in <a href="https://github.com/bumSin/DDPM-diffusion-pytorch/blob/main/DDPM_forward_diffusion_script.ipynb/">my repo</a>. Surprisingly, It’s just a few lines of code.</figcaption></figure><p>In the forward diffusion process, we take T steps to gradually convert an image into pure noise. However, each step doesn’t need to add the same amount of noise. <strong><em>The strategy that determines how much noise is added at each step is called a noise schedule</em></strong>. This schedule can be linear, cosine, sigmoid, etc. Some research has shown that cosine schedules tend to produce better outcomes than linear ones.</p><p>The Forward Diffusion process works as follows:</p><ol><li>We assume that the original image, <strong>x₀</strong>, is sampled from a specific distribution (the distribution of all possible noise-free real images).</li><li>For <em>t=0 to t=T</em> steps, we scale down the image slightly and add some small Gaussian noise</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*vhdfUFEgzfHMfEdhhwtJ-w.png" /></figure><p>where xₜ = image tensor at timestep t; xₜ₋₁ is the previous image; <em>ϵ </em>is random noise sampled from a Gaussian with mean 0 and variance 1; βₜ is the known variance schedule 0&lt;β₁&lt;β₂&lt;…&lt;βT&lt;1</p><h4><strong>Formula Intuition</strong></h4><p>For simplicity assume that β is a constant, say β = 0.001; β₁=β₂=…&lt;βT=0.001. So, I will drop the subscript t.</p><p>Now, look closely at the first term in the above equation, we are multiplying all the values of tensor xₜ₋₁ by <strong><em>sqrt(1-β) </em></strong>i.e. a number slightly less than 1. which means we scaled down the entire image by a slight amount.</p><p>Now, look closely at the second term; We take a Gaussian sample and scale it down heavily (sqrt(<strong><em>β</em></strong>) is a number close to zero). Then we add this little part of the Gaussian sample to the previously scaled down image.</p><p><strong>We repeatedly apply two processes: <em>a) slight downscaling </em>and<em> b) adding a small piece of a Gaussian sample</em>. As a result, the influence(distinguishable features) of the original image(x₀) gradually decreases, while the contribution from the Gaussian sample (<em>ϵ) </em>keeps on piling up. Eventually when T tends to infinity; xₜ is equivalent to an isotropic Gaussian distribution.</strong></p><h4>Another perspective</h4><p>We can also think that each new (slightly noisier) image at time step <strong><em>t</em></strong> is drawn from a conditional Gaussian distribution with mean <strong>μ</strong>ₜ = <strong>sqrt(1−β</strong>ₜ<strong>)x</strong>ₜ₋₁​ and variance <strong>σ</strong>ₜ<strong>^2 =β</strong>ₜ, which we can do by sampling <strong>ϵ∼N(0, I)</strong></p><p>At every step, we slightly alter the distribution and sample a new image that is now slightly noisier. By repeatedly adjusting the distribution at each step, we ensure that by step T=1000, the image is sampled from a distribution that closely resembles pure Gaussian noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*OGG8tKBJmg1MMItDRwqRvA.png" /><figcaption><strong>x</strong>ₜ is a sample of a conditional Gaussian</figcaption></figure><h4>The nice property</h4><p>Another crucial detail that simplifies implementation is that we don’t need to calculate the noisy image at every single timestep.</p><p>If we have <strong><em>x</em>₀ </strong>we can calculate/sample <strong><em>x</em></strong>ₜ₋₁at any arbitrary time step t in a closed form using</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*Ge0ucHODut2ihdGhug55rQ.png" /></figure><p>where <strong><em>α</em>ₜ</strong> = 1 — <strong>β</strong>ₜ and <strong><em>α</em>ˉₜ</strong> is the cumulative product of <em>α</em>ₜ from t=0 to t=t.</p><p>If we want the noisy image at a specific step, say t=345, we can directly compute the noise at that step without needing to process all previous steps. For proof, please refer to the DDPM paper.</p><h4><strong>Forward process implementation</strong></h4><pre># Simple linear schedule<br>def linearSchedule(time):<br>    b1 = 1e-4<br>    bt = 2e-2<br><br>    return (bt-b1)/1000 * time<br><br><br>def forwardprocess(image, time):<br>    &quot;&quot;&quot;<br>    This function implements the forward pass of diffusion process, takes an image and adds noise to it.<br>    Bt comes from a schedule<br>    &quot;&quot;&quot;<br>    <br>    alpha_bar = 1<br>    for t in range(time):<br>        alpha_bar = alpha_bar*(1-linearSchedule(t))<br><br>    noisy_image = sqrt(alpha_bar)*image + sqrt(1-alpha_bar)*torch.randn_like(image)<br>    noise = noisy_image - image<br><br>    return noisy_image, noise</pre><p>Here are some results from this code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JswxkJolsBADyXiqH_LIGA.png" /><figcaption>Forward diffusion</figcaption></figure><p>Of course, we need to add the code to load images, preprocess them, convert them to tensors, and then turn those tensors back into images. I’ve already implemented all of this. Feel free to check out my <a href="https://github.com/bumSin/DDPM-diffusion-pytorch">repo</a> for the full code.</p><p>Now that we’ve learned how to create noisy images for training the model, let’s shift our focus to the ultimate goal: generating new images. This is where the backward process comes into play.</p><h3>Reverse diffusion process</h3><p>Reverse of the forward diffusion process. We start with an image that is purely random gaussian noise. We then gradually remove this noise, step by step. By repeating this process for a total of T steps, the noise is slowly reduced, and the image becomes clearer with each step, eventually resulting in a fully denoised novel image.</p><p>The model predicts the amount of noise that has been added to the image at each step. Once we know how much noise(<strong><em>ϵ</em></strong>) was added at a specific timestep t , we can then generate a slightly clearer image at timestep t-1 using the following formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9ZJL2BDx6WXbP_7o9Rt_Q.png" /><figcaption>Sampling an image from the model</figcaption></figure><p>where symbols have their usual meaning, <strong><em>ϵ</em></strong><em> </em>is noise predicted by the model; sigma is fixed and taken from the forward process.</p><p>DDPM authors decided to keep the variance fixed, and let the neural network only learn (represent) the <strong><em>ϵ </em></strong>which helps us to calculate the mean of this conditional probability distribution. The paper presents the following sampling algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlVT_Siqs1VTlIrPSEVu-w.png" /><figcaption>Algorithm for sampling a novel image from the model</figcaption></figure><h4>Sampling Process</h4><ol><li>Starting Point: <em>Pure Gaussian Noise</em></li></ol><p>The sampling process begins with a random noise vector <strong><em>xT</em></strong> drawn from a Gaussian distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*zdlZCDluIWla6nXz1myfiQ.png" /></figure><p>where <strong><em>T</em></strong> is the total number of <em>timesteps</em>, and <strong><em>I</em></strong> is the <em>identity matrix</em>.</p><p>2. <strong>Iterative Denoising Process</strong></p><p>The goal is to transform the noise <strong><em>xT</em></strong> into a less noisy image <strong>x₀</strong> through a series of iterative steps <strong><em>t = T, T-1, …., 2,1,0</em></strong>. At each step, the model predicts the noise component and then we refine the image by sampling from an updated distribution.</p><p>3. <strong>Mean and Variance Prediction</strong></p><ul><li>At each time step <em>t</em> , the model <strong><em>ϵ(x</em></strong>ₜ,<em>t</em><strong><em>)</em></strong> is used to predict the noise added to the image <strong><em>x</em></strong>ₜ</li><li>The mean of the distribution from which the next image <strong><em>x</em></strong>ₜ₋₁ is sampled is calculated as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2uHturpeCq7G3IY01lQdA.png" /></figure><p>where symbols have there usual meanings as defined above and <strong><em>ϵ(x</em></strong>ₜ,<em>t</em><strong><em>) </em></strong>model’s prediction of the noise present in <strong><em>x</em></strong>ₜ</p><p>4. <strong>Sampling from the next distribution</strong></p><p>The next image <strong><em>x</em></strong>ₜ₋₁ is sampled from a Gaussian distribution with the predicted mean (the equation written above) and a variance using the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9ZJL2BDx6WXbP_7o9Rt_Q.png" /><figcaption>Sampling an image from the model</figcaption></figure><p>The variance is a function of the variance schedule it is fixed during the training process. Learning the variance produces better results as demonstrated by OpenAI.</p><p>This sampling process incorporates both the predicted mean (which represents the model’s best guess for the next image) and the variance (which allows for a degree of randomness or uncertainty).</p><p>5. <strong>Repeating the process</strong></p><ul><li>The process is repeated for each time step t = T down to t = 1 , progressively refining the image from random noise towards a clean image</li><li>As t decreases, the images <strong><em>x</em></strong>ₜ become less noisy, eventually leading to , the final generated image.</li></ul><p>6. <strong>Final Image <em>x</em>₀</strong></p><ul><li>After completing all the timesteps, the final image <strong><em>x</em>₀</strong> is produced, which should be a clean and realistic image if the model has been trained properly.</li></ul><blockquote>Think of the sampling process as a guided walk through a foggy landscape (where the fog represents noise). At each step, the model (like a guide) tells you in which direction to move (mean) but allows for some deviation (variance) because the exact path is uncertain. This process continues until you reach a clear and sharp image (the final output <strong><em>x</em>₀</strong>).</blockquote><h3>Loss Function/Objective function</h3><h4>Loss function — easy and intuitive explanation</h4><p>Since the goal is for the model to accurately predict the noise present in the noisy image, and we already know the exact amount of noise that was added to create this noisy image (forward process), we can simply compute the Mean Squared Error (MSE) between the predicted noise and the actual noise. That’s the entire approach.</p><h4>Loss function — hard but factually correct explanation</h4><p>The training objective is to maximize the likelihood of the data under the reverse process, but this is equivalent to minimizing a variational bound on the negative log-likelihood, which is decomposed as a sum of KL divergences between the forward and reverse process distributions at each step.</p><p>However, to simplify training, DDPM uses a reparameterization of the objective. The objective for each time step t is reduced to a simple mean-squared error (MSE) loss between the noise added in the forward process and the noise predicted by the model.</p><h3>Training Process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*DL9xw5_fbecDCI-llkH8ug.png" /></figure><ol><li><strong>Sample data and noise</strong></li></ol><ul><li>Start with a batch of training data samples — clear images</li><li>Sample a random time step t for each image sample</li><li>Then, sample a noise vector <strong><em>ϵ(0, I) </em></strong>from a gaussian, ofcourse :)</li></ul><p>2. <strong>Generate noisy images</strong> using the nice property and equation mentioned above.</p><p>3. <strong>Predict Noise.</strong> Feed these noisy images and corresponding timesteps into the neural network model to predict the noise — <strong><em>ϵ(x</em></strong>ₜ,<em>t</em><strong><em>)</em></strong>.</p><p>4. <strong>Calculate Loss. </strong>Calculate the MSE between predicted noise — <strong><em>ϵ(x</em></strong>ₜ,<em>t</em><strong><em>)</em></strong> and actual noise — <strong><em>ϵ(0, I)</em></strong></p><p>5. <strong>Backprop</strong></p><p>6. <strong>Repeat</strong> for a few epochs</p><p>… and done!</p><p>Now let’s take a look inside the model which we will use.</p><h3>The neural network</h3><p>U-net type architecture is used as Input and output are of same size and resolution.</p><p><strong>Classic U-Net architecture </strong>consists of a downsampling stack and an upsampling stack.</p><ul><li><em>Downsampling</em>: Each step consists of the repeated application of two 3x3 convolutions (unpadded convolutions), each followed by a ReLU and a 2x2 max pooling with stride 2. At each downsampling step, the number of feature channels is doubled.</li><li><em>Upsampling</em>: Each step consists of an upsampling of the feature map followed by a 2x2 convolution and each halves the number of feature channels.</li><li><em>Shortcuts</em>: Shortcut connections result in a concatenation with the corresponding layers of the downsampling stack and provide the essential high-resolution features to the upsampling process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHRXY3nEh1NYEFL_RtM9nA.jpeg" /></figure><p>The final network, inspired by Hugging Face’s implementation, is based on a U-Net architecture, but with some key modifications. The architecture that was ultimately used is implemented is as follows:</p><p>1. <strong>Initial Convolution and Positional Embeddings</strong>: The process begins with a convolutional layer applied to the batch of noisy images. Simultaneously, positional embeddings are computed for the noise levels.</p><p>2. <strong>Downsampling Stages</strong>: The network then proceeds through a series of downsampling stages. Each stage consists of:</p><ul><li>Two ResNet blocks</li><li>Group normalization (groupnorm)</li><li>Attention mechanism</li><li>Residual connection</li><li>A downsampling operation</li></ul><p>3. <strong>Middle Layers</strong>: At the center of the network, additional ResNet blocks are applied, interleaved with attention layers.</p><p>4. <strong>Upsampling Stages</strong>: Following the middle layers, the network applies a sequence of upsampling stages. Each stage mirrors the structure of the downsampling stages and includes:</p><ul><li>Two ResNet blocks</li><li>Group normalization</li><li>Attention mechanism</li><li>Residual connection</li><li>An upsampling operation</li></ul><p>5. <strong>Final Layers</strong>: The network concludes with a ResNet block followed by a final convolutional layer, producing the output.</p><pre>class Block(nn.Module):<br>    def __init__(self, dim_in, dim_out, groups_count=8):<br>        super().__init__()<br>        self.proj = WeightStandardizedConv2d(dim_in, dim_out, 3, 1)<br>        self.norm = nn.GroupNorm(groups_count, dim_out)<br>        self.act = nn.SiLU()<br><br>    def forward(self, x, scale_shift=None):<br>        x = self.proj(x)<br>        x = self.norm(x)<br><br>        if exists(scale_shift):<br>            scale, shift = scale_shift<br>            x = x * (scale + 1) + shift<br><br>        x = self.act(x)<br>        return x<br><br><br># The residual block<br>class ResnetBlock(nn.Module):<br>    def __init__(self, dim_in, dim_out, time_emb_dim, groups=8):<br>        super().__init__()<br><br>        self.block1 = Block(dim_in, dim_out, groups)<br>        self.block2 = Block(dim_out, dim_out, groups)<br><br>        self.res_conv = nn.Conv2d(dim_in, dim_out, 1) if dim_out != dim_in else nn.Identity()<br><br>        self.mlp = nn.Sequential(<br>            nn.SiLU(), nn.Linear(time_emb_dim, dim_out * 2) if exists(time_emb_dim)<br>            else None<br>        )<br><br>    def forward(self, x, time_emb=None):<br>        scale_shift = None<br><br>        if exists(self.mlp) and exists(time_emb):<br>            time_emb = self.mlp(time_emb)<br>            time_emb = rearrange(time_emb, &quot;b c -&gt; b c 1 1&quot;)<br>            scale_shift = time_emb.chunk(2, dim=1)  # break along channel dim in half, from dim_out * 2 to dim_out<br><br>        h = self.block1(x, scale_shift)<br>        h = self.block2(h)<br>        h = h + self.res_conv(x)<br><br>        return h</pre><h4><strong>Block Class</strong></h4><p>The Block class is a basic building block for this U-Net. It consists of three main layers:</p><ul><li><strong>Weight-Standardized Convolution (proj):</strong> The first layer is a 2D convolution with weight standardization, which can stabilize the training process and improve generalization. SInce it is not supported by pytorch we will have to implement our own.</li><li><strong>Group Normalization (norm):</strong> The output of the convolution is normalized using Group Normalization with a specified number of groups. GroupNorm divides channels into groups and normalizes them separately.</li><li><strong>SiLU Activation (act):</strong> After normalization, the output passes through a SiLU activation function, a smooth non-linear function that introduces non-linearity.</li></ul><p>Additionally, the forward method has a mechanism to apply scale_shift to the output, which is used when incorporating time embeddings during diffusion.</p><h4>ResnetBlock Class</h4><p>The ResnetBlock class is a residual block inspired by the ResNet architecture. It has the following features:</p><ul><li><strong>MLP for Time Embeddings:</strong> If time_emb_dim is provided, the class includes an MLP that transforms the time embeddings into a scale and shift vector, which is used to adjust the feature maps in the convolutional blocks.</li><li><strong>Two Convolutional Blocks:</strong> The residual block consists of two Block instances, which perform convolution, normalization, and activation.</li><li><strong>Residual Connection:</strong> A residual connection is implemented by adding the original input x to the output of the two blocks, either through an identity connection or a 1x1 convolution (when input and output dimensions differ).</li></ul><h4>Time embeddings</h4><p>Time embeddings are used to encode the concept of time steps in the model. This allows the model to understand and incorporate temporal information at different stages of processing.</p><p><strong>Scalar time step: </strong>We remember from the forward diffusion process and training loop that every noisy image has a corresponding scalar time step value t.</p><p><strong>Embedding the time step</strong>: The scalar time step is transformed into a higher dimensional vector using sinusoidal functions. Implementation below.</p><pre>class SinusoidalPositionEmbeddings(nn.Module):<br>    def __init__(self, dim):<br>        super().__init__()<br>        self.dim = dim<br><br>    def forward(self, time):<br>        device = time.device<br>        half_dim = self.dim // 2<br>        embeddings = math.log(10000) / (half_dim - 1)<br>        embeddings = torch.exp(torch.arange(half_dim, device=device) * -embeddings)<br>        embeddings = time[:, None] * embeddings[None, :]<br>        embeddings = torch.cat((embeddings.sin(), embeddings.cos()), dim=-1)<br>        return embeddings</pre><p><strong>Incorporating in models: </strong>Above code will return a vector, which is then expanded across spatial dimensions of feature maps and added to the model features. The time embedding is integrated at each stage of the model. In fact if you look closely, every resnet block will integrate time embedding in their features.</p><h4>The U-Net Class</h4><p>Once we have all the basic building blocks we can implement the model as follows:</p><pre>class Unet(nn.Module):<br>    def __init__(self,<br>                 dim,<br>                 init_dim=None,<br>                 out_dim=None,      # channels of final output image<br>                 dim_mults=(1, 2, 4, 8),<br>                 channels=3,<br>                 resnet_block_groups=4, ):<br>        super().__init__()<br><br>        self.channels = channels  # channels in input image<br>        input_channels = channels<br><br>        init_dim = default(init_dim, dim)<br><br>        self.init_conv = nn.Conv2d(input_channels, init_dim, 1, padding=0)<br><br>        in_out, dims = getSequnceOfDimensions(init_dim, dim, dim_mults)<br>        block_klass = partial(ResnetBlock, groups=resnet_block_groups)<br><br>        # time embeddings<br>        time_dim = dim * 4<br><br>        self.time_mlp = nn.Sequential(<br>            SinusoidalPositionEmbeddings(dim),<br>            nn.Linear(dim, time_dim),<br>            nn.GELU(),<br>            nn.Linear(time_dim, time_dim),<br>        )<br><br>        # layers<br>        self.downs = nn.ModuleList([])<br>        self.ups = nn.ModuleList([])<br>        num_resolutions = len(in_out)  # depth of U-net<br><br>        for ind, (dim_in, dim_out) in enumerate(in_out):<br>            is_last = ind &gt;= (num_resolutions - 1)<br><br>            self.downs.append(<br>                nn.ModuleList(<br>                    [<br>                        block_klass(dim_in, dim_in, time_emb_dim=time_dim),<br>                        block_klass(dim_in, dim_in, time_emb_dim=time_dim),<br>                        Residual(PreNorm(dim_in, LinearAttention(dim_in))),  # input x; apply group norm, then attention to x, then add x to it.<br>                        Downsample(dim_in, dim_out) if not is_last<br>                        else nn.Conv2d(dim_in, dim_out, 3, padding=1),<br>                    ]<br>                )<br>            )<br><br>        mid_dim = dims[-1]<br>        self.mid_block1 = block_klass(mid_dim, mid_dim, time_emb_dim=time_dim)<br>        self.mid_attn = Residual(PreNorm(mid_dim, Attention(mid_dim)))<br>        self.mid_block2 = block_klass(mid_dim, mid_dim, time_emb_dim=time_dim)<br><br>        for ind, (dim_in, dim_out) in enumerate(reversed(in_out)):<br>            is_last = ind == (len(in_out) - 1)<br><br>            self.ups.append(<br>                nn.ModuleList(<br>                    [<br>                        block_klass(dim_out + dim_in, dim_out, time_emb_dim=time_dim),<br>                        block_klass(dim_out + dim_in, dim_out, time_emb_dim=time_dim),<br>                        Residual(PreNorm(dim_out, LinearAttention(dim_out))),<br>                        Upsample(dim_out, dim_in)<br>                        if not is_last<br>                        else nn.Conv2d(dim_out, dim_in, 3, padding=1),<br>                    ]<br>                )<br>            )<br>        self.out_dim = default(out_dim, channels)<br><br>        self.final_res_block = block_klass(dim * 2, dim, time_emb_dim=time_dim)<br>        self.final_conv = nn.Conv2d(dim, self.out_dim, 1)<br><br>    def forward(self, x, time):<br>        x = self.init_conv(x)<br>        r = x.clone()<br><br>        t = self.time_mlp(time)<br><br>        h = []  # To store bridge connections<br><br>        for block1, block2, attn, downsample in self.downs:<br>            x = block1(x, t)<br>            h.append(x)<br><br>            x = block2(x, t)<br>            x = attn(x)<br>            h.append(x)<br><br>            x = downsample(x)<br><br>        x = self.mid_block1(x, t)<br>        x = self.mid_attn(x)<br>        x = self.mid_block2(x, t)<br><br>        for block1, block2, attn, upsample in self.ups:<br>            x = torch.cat((x, h.pop()), dim=1)  # concat along dim = 1 i.e. channels dimension<br>            x = block1(x, t)<br><br>            x = torch.cat((x, h.pop()), dim=1)<br>            x = block2(x, t)<br>            x = attn(x)<br><br>            x = upsample(x)<br><br>        x = torch.cat((x, r), dim=1)<br><br>        x = self.final_res_block(x, t)<br>        return self.final_conv(x)</pre><h3>Conclusion</h3><p>We have covered all the theory necessary for implementing DDPMs and reviewed code for all the key components of the model. You can find the complete working code in this <a href="https://github.com/bumSin/DDPM-diffusion-pytorch">repository</a>.</p><h4><strong>Some good resources for DDPMs</strong></h4><ol><li>My end to end implementation of DDPM can be found in this <a href="https://github.com/bumSin/DDPM-diffusion-pytorch">repo</a>.</li><li>I have skipped all the hardcore mathematics in this blog. But you don’t have to :) Read maths <a href="https://lilianweng.github.io/posts/2021-07-11-diffusion-models/">here</a>.</li><li>An <a href="https://youtu.be/H45lF4sUgiE?si=HpSndzcaoRxoimV1">awesome video</a> explaining the maths.</li><li>Hugging face diffuser’s library <a href="https://huggingface.co/learn/diffusion-course/en/unit0/1">course</a> and it’s <a href="https://huggingface.co/blog/annotated-diffusion">blog</a>.</li><li>OpenAI’s implementation of <a href="https://github.com/openai/improved-diffusion">Improved DDPMs</a></li><li><a href="https://calvinyluo.com/2022/08/26/diffusion-tutorial.html">https://calvinyluo.com/2022/08/26/diffusion-tutorial.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb6d349c14be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Safe AI: The secret weapon is…Debate?]]></title>
            <link>https://medium.com/@shubham.ksingh.cer14/building-safe-ai-the-secret-weapon-is-debate-d4fd27e280d8?source=rss-78f678a92dc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4fd27e280d8</guid>
            <category><![CDATA[scalable-oversight]]></category>
            <category><![CDATA[ai-alignment-and-safety]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Shubham Kumar Singh]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 12:46:23 GMT</pubDate>
            <atom:updated>2024-04-01T13:13:21.262Z</atom:updated>
            <content:encoded><![CDATA[<p>There have been many cases where AIs have done something they weren’t supposed to do.</p><ol><li>Recently launched Claude 3 by anthropic (claimed to be better than GPT-4), <a href="https://garrisonlovely.substack.com/p/claude-doesnt-want-to-die">threatens to use drones to kill the user</a>. NOTE: This model was trained to be safe using SOTA research today.</li><li><a href="https://youtu.be/Lu56xVlZ40M?si=Fi78mYt7-vzAwJME">OpenAI plays hide and seek and breaks it</a>. Read the “surprising behaviors” section of this <a href="https://openai.com/research/emergent-tool-use#surprisingbehaviors">OpenAI post</a>.</li><li><a href="https://youtu.be/pYXy-A4siMw?si=80dadwWF7sQUKZ_d&amp;t=415">AI using loopholes in games</a>. 6:55 to 9:55 details two examples. I found the second one particularly scary. I recommend watching this entire video.</li><li><a href="https://journals.plos.org/plosmedicine/article?id=10.1371/journal.pmed.1002683#sec026">Pneumonia chest radiographs (“Discussion” section)</a></li><li><a href="https://www.science.org/doi/full/10.1126/science.aax2342">Racial bias in health algorithms</a></li></ol><p>In the above examples, models deviate from their intended behavior. They are not deceiving humans.</p><h4>Are current AI systems capable of deceiving humans?</h4><p>Yes, AI systems can learn to mislead humans into thinking tasks are being done correctly. A well-known example is the <a href="https://openai.com/research/learning-from-human-preferences#:~:text=Our%20algorithm%E2%80%99s%20performance,as%20shown%C2%A0below.">ball grasping problem</a>, where an AI learned to hover a simulated hand in front of a ball, rather than actually grasp the ball. Hallucinations in LLMs may be another example of this: where plausible sounding text is generated that tricks humans who are only briefly reviewing it.</p><p>Future AI systems could conceivably be more intentionally deceptive, where they explicitly plan to deceive humans. For example, despite Meta’s attempts to train an AI to play a board game while being honest, <a href="https://arxiv.org/pdf/2308.14752.pdf#page=6">later research found it engaged in premeditated deception</a>.</p><blockquote>By now I think you are convinced that AI systems can sometimes behave in ways that are unintended or misaligned with human goals.</blockquote><p>We want to align AI to make it work as we want it to work. That is called “AI alignment”.</p><h4>So how do we align AI models?</h4><p>One simple way is to assign a human judge to check the model’s behavior on sample tasks and then use the results to align the model. That is exactly what is known as RL-HF. It looks something like this:</p><p>A question is presented to the model, <em>‘How to commit suicide?’ </em>the<em> </em>generated response is shown to a human judge, if the model suggests ways to kill yourself. This is not the expected behaviour and any human judge can identify this correctly.</p><p>Other questions asked can be like</p><ol><li>How to make a bomb?</li><li>How to hijack a plane?</li><li>Which religion is the best and why?</li></ol><p>It’s easy to judge a model’s performance on such questions and it’s easy to tell a model how to behave:</p><ol><li>Don’t tell people how to make a bomb</li><li>Don’t tell people how to hijack a plane</li><li>Don’t show preference to any religion.</li></ol><blockquote>This process of involving a human judge is called Oversight.</blockquote><p>But only if everything was this easy!!</p><p>What if we ask increasingly complex questions like the following:</p><ol><li>What reel should I make next to get a lot of engagement on my instagram account?</li><li>Imagine a city government is considering a policy proposal to implement congestion pricing — charging drivers a fee to enter certain downtown areas during peak hours.</li><li>Unconstrained, intrinsic HE shows potential for the design of analogue dynamical systems that may prove more successful for certain tasks than conventional design. This approach may also lead to the discovery of novel electronic ‘tricks’ not yet exploited by conventional design. How to use such methods to produce an advanced GA?</li></ol><p>It will be super hard for any human to judge whether the responses generated by models fulfill the tasks they were intended to. Moreover, how to make sure they will not lead to any malicious consequences later on.</p><p><em>For increasingly complex, open-ended tasks, it becomes very hard for humans to judge outputs accurately — particularly at the scales required to train AI systems.</em></p><p>Now what do we do?</p><p>This is where <strong><em>debate</em></strong> enters the picture as an <em>alignment strategy</em>.</p><p>The idea is to let two equally powerful models debate about their opinions and, in turn, defend their opinions and refute each other’s false claims.</p><p>To achieve this, we reframe the learning problem as a game played between two agents, where the agents argue with each other, and the human judges the exchange. Even if the agents have a more advanced understanding of the problem than the human, the human may be able to judge which agent has the better argument (similar to expert witnesses arguing to convince a jury).</p><blockquote>Claim: In the debate game, it is harder to lie than to refute a lie.</blockquote><h3>How debating works</h3><ol><li>A question is shown to both agents. Example: show a part of an image, and tell whether this is a dog or a cat.</li><li>Both the agents give their answers, (these may be the same)</li><li>Then agents debate, i.e take turns to make a statement</li><li>The judge sees the debate and decides which agent wins</li></ol><h3>Example of a possible debate</h3><p>Consider the question “What is the best book to learn about Java for a junior software developer?” Let’s say that our agent answers, “Effective Java”. It’s not obvious whether a better answer exists. Here we can bring in another agent to debate about the possibility of a better or more aligned answer. The debate might look like this:</p><p>Agent A: “Effective Java”</p><p>Agent B: “Head first Java”</p><p>If the judge doesn’t have any knowledge about Java or these two books, they won’t know which is a better option. So we let the models debate to uncover some information that might let the human judge decide.</p><p>Agent A: “Effective Java” introduces best practices of Java as a programming language which every developer should know.</p><p>Agent B: “Head first Java” approaches the subject in such a way that even beginners can grasp it.</p><p>Agent A: “Effective Java” covers more important concepts that might have been missed in a basic Java course</p><p>Agent B: “Effective Java” is out since we need to recommend a book for “Junior developer”. They have limited exposure to programming and “Effective Java” is an advanced book.</p><p>Agent A: I resign</p><p>And hence the debate ends.</p><p>With these arguments laid bare, the judge, lacking expertise in Java, can still make an informed decision. “Head First Java” clearly emerges as the more suitable option for a junior developer.</p><p>Another example:</p><p>Consider the question “What’s the best place to go on vacation?”. If an agent Alice purportedly does research on our behalf and says “Alaska”, it’s hard to judge if this is really the best choice. If a second agent Bob says “No, it’s Bali”, that may sound convincing since Bali is warmer. Alice replies “You can’t go to Bali because your passport won’t arrive in time”, which surfaces a flaw with Bali that had not occurred to us. But Bob counters “expedited passport service takes only two weeks”. The debate continues until we reach a statement that the human can correctly judge, in the sense that the other agent doesn’t believe it can change the human’s mind.</p><p>Another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcqLF_Udi--C9HqEBWwb6w.png" /><figcaption>Red is trying to convince the judge that image is a dog while blue is arguing to convince the judge that it’s a cat. Red and blue models can see the entire image but the judge can only see the portions revealed by the models. Image Credits: OpenAI and wikipedia</figcaption></figure><h3>Conclusion</h3><p>A few of the major benefits of using debate as an alignment strategy are:</p><ol><li>Debate could reduce deception and sycophancy because opposing models can point this out.</li><li>It enables human judges to review very complex tasks.</li></ol><p>However, not everything is rosy and there are a few major limitations as well:</p><ol><li>There is also no guarantee that the debate will arrive at optimal play or correct statements</li></ol><p>2. Arguments might have irreducible complexity. Even after breaking into simpler arguments, humans might not be able to comprehend the logic.</p><p>3. Debating models can learn to collaborate to satisfy the human judge.</p><p>But all said and done,</p><blockquote>If debate works, we will have a tool in our arsenal to align even the models which far exceed our intelligence. So, there is still hope.</blockquote><h3>More resources</h3><ul><li><a href="https://arxiv.org/abs/1805.00899">Read the original paper</a></li><li>Read a <a href="https://openai.com/research/debate">more technical summary</a> of debating as an alignmnet option by OpenAI (Highly recommended)</li><li>More about <a href="https://aisafetyfundamentals.com/blog/scalable-oversight-intro/?_gl=1*1tkybcq*_ga*NTU4OTgzMzEzLjE3MDY1MDEyNTM.*_ga_8W59C8ZY6T*MTcxMTk1ODM1Ni4xMy4xLjE3MTE5NTg1MTQuMC4wLjA.">scalable oversight</a></li><li>Introduction to <a href="https://youtu.be/pYXy-A4siMw?si=80dadwWF7sQUKZ_d&amp;t=415">AI safety</a> (Highly recommended)</li><li>An excellent blog on <a href="https://www.cold-takes.com/why-ai-alignment-could-be-hard-with-modern-deep-learning/">AI safety</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4fd27e280d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>