Sohaib Arif — AI Safety Research

Notes on AI safety for local & embedded models

Fine Tuning Code-Gen model on AMD GPU

Introduction

While I save up for a 3d printer to advance my Kria KR260 project I went back to my other project about tool use verification in LLMs running on consumer GPUs. I have been reading several sources and even got two free certifications along the way (Google Generative AI Leader and Hugging Face Smol Course). The smol course gets you up and running with the Transformers library and related libraries like TRL (Transformer Reinforcement Learning) and datasets. It is a good way to refresh your knowledge if you have forgotten some concepts or have been heavily relying on wrappers like LangGraph. Another good resource I have been reading is a book from Manning Publications called Domain-Specific Small Language Models by Guglielmo Iozzia. Both are great to learn some of the theory from and one of them is free so I won't repeat any of the content here. But both of them had a gap when it comes to testing generated content specifically their code generation. Chapters 3 and 7 of the book cover code generation, specifically with respect to generating Manim code. Manim is the tool built and used by YouTube educator 3Blue1Brown. The docs for its community fork (not the original) can be found at this link. It is a niche tool for math animations, originally built for 3Blue1Brown's videos, unlike more general tools such as PyGame that could also be used for animation. Therefore most LLMs, especially smaller ones, are not able to directly generate code for this Python framework. It does not have extensive documentation so you can't use RAG or MCP as effectively as other more standard tools either. And probably most importantly in the context of learning local LLM fine tuning, there is a dataset of instructions and reference outputs that models can easily be fine tuned on. The book in chapter 3 uses this dataset and after the course you can easily adapt it to use it. But there are two major gaps. One is that evaluating the generated code has some parts missing from the book and there is some justification for it. The other is that both assume either a consumer Nvidia GPU or the use of cloud services (in the case of Hugging Face). So training on commonly used AMD GPUs is skipped by both. The aim of this write-up is to cover both gaps without repeating any of the content from either.

Why most sources use Nvidia GPUs

A lot of people I've talked to, even on the technical side, seem to think AI is a new thing. It isn't. The field's roots go back to the 1940s, and so does the core idea behind deep learning, the technique large language models are built on. In 1943, Warren McCulloch and Walter Pitts described a simple mathematical model of a neuron. In 1958, Frank Rosenblatt built the perceptron, a single layer of these neurons that could actually learn its weights. At its core it was little more than output = weight * input + bias, passed through a threshold. The problem is that a single layer can only draw straight-line boundaries between categories, which isn't enough for most real problems. In 1969, Marvin Minsky and Seymour Papert famously showed it couldn't even learn the simple XOR function. Stacking multiple layers solves this, and in 1986 Rumelhart, Hinton and Williams popularized backpropagation, the algorithm used to train multi-layer networks. But for decades there wasn't enough computing power or data to make large networks practical, and the approach was largely sidelined.

That changed in 2012. Alex Krizhevsky, working with Ilya Sutskever and Geoffrey Hinton, entered a deep convolutional network, now known as AlexNet, in the ImageNet competition. It had more layers than earlier networks, used techniques like ReLU activations (which help the training signal flow through many layers) and dropout, and was trained on about 1.2 million labeled images. It won by a huge margin, with a top-5 error rate of about 15% against 26% for the runner-up, and it convinced much of the field that deep learning worked. Neural networks had seen real use before (LeNet was reading handwritten digits on bank checks in the 1990s), but AlexNet was the turning point. This is where the GPU part of the story comes in. AlexNet was trained on two Nvidia GTX 580 GPUs using CUDA (Compute Unified Device Architecture), Nvidia's proprietary platform for general-purpose GPU computing, first released in 2007. An alternative called OpenCL had been around since 2008. Despite the name, OpenCL is an open standard rather than an open-source library: the Khronos Group maintains it and each hardware vendor implements it. It therefore can run on Nvidia, AMD and Intel hardware. But the big 2012 win happened on CUDA, and to their credit, Nvidia capitalized on it. They released cuDNN, a library of optimized deep learning building blocks, in 2014, and they have invested heavily in building training courses for developers ever since.

So when the first wave of deep learning frameworks appeared, including Theano, the Lua-based Torch and Caffe, they were built around CUDA. They were mostly written in C and C++, with GPU kernels written directly in CUDA. Some had OpenCL support through experimental backends or forks (there was an OpenCL branch of Caffe, for example), but it was always second-class. Deep learning became much more accessible with Python frameworks like TensorFlow (2015) and PyTorch (2016), and with the Keras wrapper (2015), but underneath they relied on the same CUDA and cuDNN code. Every new feature deepened that dependence and widened the gap with OpenCL. So while AMD GPUs could do deep learning in theory during the boom of the mid-2010s, in practice the cost of rewriting kernels, plus the rush to get new models working, left AMD on the sidelines.

Fast forward to today, and the picture is much better. AMD has its own platform, ROCm (released in 2016). It includes HIP, a C++ dialect designed to make porting CUDA code straightforward. PyTorch now ships official ROCm builds. Outside PyTorch, OpenCL has largely faded, and some inference tools, such as llama.cpp, use Vulkan for GPU support across vendors. For most fine-tuning workflows, the same PyTorch code runs on AMD as on Nvidia. The main hurdle is installation, and there are good guides for that, including some from AMD itself. Some libraries with hand-written CUDA kernels still get Nvidia support first, so check compatibility for anything outside core PyTorch. One thing that confuses newcomers: PyTorch's ROCm builds deliberately reuse the torch.cuda interface. On an AMD GPU you still write torch.device("cuda"), and torch.cuda.is_available() returns True. That's expected. Your AMD GPU is being used. (Intel GPUs use torch.xpu instead, and newer PyTorch versions add a device-agnostic torch.accelerator API.)

Aside: AI Winter and Deep Learning You may come across the term "AI Winter." It refers to periods when funding and interest in AI collapsed, roughly the mid-1970s and the late 1980s to early 1990s. Limited computing power was part of the reason, but so were overpromising and the funding cuts that followed when the promised results didn't appear. You may also wonder why the field is called "Deep Learning." "Deep" refers to the number of layers in a neural network. By stacking many layers, these networks can learn much more complex patterns than a single layer can.

Aside: GPU Compatibility When AMD entered the deep learning market, and as recently as 2024, GPUs from the consumer Radeon 6xxx series were not supported and neither were lower-end Radeon 7xxx series. With CUDA the lowest end Nvidia GPU would still work for learning while AMD made a distinction between consumer and workstation GPUs. When I was researching which GPU to buy for my desktop, the matrix of that version of ROCm had the Radeon RX 7900 GRE as the lowest supported GPU. This was in 2024 when the ROCm version was 6.2.1. With the current ROCm 10.2 the much more affordable Radeon RX 7600 is the lowest supported dedicated GPU. There are also many integrated GPUs now supported by ROCm which you can see under the AMD Ryzen tab of the matrix. When installing ROCm or buying an AMD GPU for learning, make sure to check the compatibility matrix on the page.

Memory and Crashes

If you are running models locally on a computer that you still want to use while training runs, there are two things to set before PyTorch loads: which GPU to use, and how PyTorch manages GPU memory. First, if you are using an AMD CPU with an AMD GPU, you may have something called an APU. An APU is a CPU with a built-in GPU that takes memory from the system RAM instead of dedicated VRAM. Some of AMD's CPUs are actually APUs. For training locally, you likely want to use only your dedicated GPU and keep using your computer while training runs in the background. To do this GPU selection and memory configuration, you need to put the following lines above all PyTorch code.

import os
os.environ["HIP_VISIBLE_DEVICES"] = "0"
os.environ["PYTORCH_HIP_ALLOC_CONF"] = "expandable_segments:True"

PyTorch keeps memory it has freed in a cache so it can reuse it, and over a long training run that cache can become fragmented. This means that there is enough free memory in total, but not in one piece big enough for the next allocation. Setting expandable_segments:True lets PyTorch grow its existing memory blocks instead of allocating new fixed-size ones, which reduces fragmentation.

Another solution is to cap the percentage of memory that a torch process is allowed to use. You can do this with

import torch 
torch.cuda.set_per_process_memory_fraction(0.85)

Full Fine-Tuning vs LoRA and Memory Limitations

At this point both the book and the Hugging Face course can be followed mostly directly. The difference is that the book starts with a smaller model (GPT2) and the Hugging Face Smol course starts with SmolLM3 (which is significantly larger than GPT2). Because of the model sizes, what you can do on a consumer GPU is different. You can completely fine tune the GPT2 model like a normal deep learning model, but for larger models like SmolLM3 you need to use parameter-efficient fine-tuning methods such as LoRA, which adapt the model to your task by training small adapter layers while the original weights stay frozen.

The book is also able to use hyper-parameter optimization using the optuna library which searches the best hyper-parameters for your task before running the full training loop. The Hugging Face course skips this because it would take longer and potentially result in crashes. Another big difference is that the book is focused on local models so later chapters go deeper into how you can utilize the limited GPU memory more effectively for both training and inference. The course on the other hand does try to push you into using Hugging Face's paid services. There are advantages and disadvantages to both. With the Hugging Face service you may save initial cost or some learning friction since the environment is preconfigured for you. Additionally, you can use larger models and fine tune larger models with larger datasets. The problem is that it may end up costing more in the long run in monthly + usage fees and if you already have a GPU it is probably a better idea to learn to use that first. You may think you need larger models in general but try fine tuning on your use case first with a smaller model.

Aside: Using Notebooks vs Scripts I did mention notebooks because even the book's code on GitHub has notebooks but for something as resource intensive as Fine Tuning an LLM, I highly recommend not using Notebooks. They either run in memory hungry browsers or in VSCode which itself is built on Electron. Electron is a framework that allows people to easily build cross-platform applications but it is internally just a browser so it is also very RAM intensive. Therefore, I suggest using something like the Zed IDE or writing and running scripts to train models after checking for correctness with 2 or 3 quick epochs in a notebook if needed.

Getting Generated Code

The book and the course use different patterns that the generator is trained on. You can follow either version as long as the prompt and extracted code is consistent. For testing it's fine to run individual prompts but for a full evaluation the book shows a great option by using the test set and having it generate code for each prompt. The result is stored in a CSV along with reference outputs. Note that all the code here is snippets, not full scripts, so change it as needed.

import os

os.environ["HIP_VISIBLE_DEVICES"] = "0"
os.environ["PYTORCH_HIP_ALLOC_CONF"] = "expandable_segments:True"
import csv
import json
from pathlib import Path

import torch
from datasets import load_dataset
from transformers import GPT2LMHeadModel, GPT2Tokenizer

dataset = load_dataset("Edoh/manim_python")
model_dir = "./gpt2-manim-python-finetuned"

tokenizer = GPT2Tokenizer.from_pretrained(model_dir)

model  = GPT2LMHeadModel.from_pretrained(model_dir)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model.to(device)

model.eval()

def generate_output(instruction:str, max_new_tokens:int=500, repetition_penalty:float=1.2, do_sample:bool=True):
    prompt = f"Instruction: {instruction}\n Output:"
    input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)
    generated_ids = model.generate(
        input_ids,
        max_new_tokens=max_new_tokens,
        repetition_penalty=repetition_penalty,
        do_sample=do_sample,
        eos_token_id=tokenizer.eos_token_id,
    )

    generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)

    output_start = generated_text.find("Output:")
    if output_start != -1:
        output_text = generated_text[output_start+len("Output:"):].strip()
    else:
        output_text = generated_text.strip()
    return output_text

output_csv = Path("from_book","gpt2_manim_python_test_outputs.csv")
generation_params = {"max_new_tokens":500,"repetition_penalty":1.2,"do_sample":True}
output_csv.parent.mkdir(exist_ok=True)
params_json = Path("from_book", "params.json")
with open(params_json, "w") as f:
    json.dump(generation_params, f)
with open(output_csv, mode="w", newline="", encoding="utf-8") as csvfile:
    writer = csv.DictWriter(csvfile,
        fieldnames=["instruction", "reference_output", "generated_output"])
    writer.writeheader()

    for example in dataset["test"]:
        instruction = example["instruction"]
        generation_params['instruction'] = instruction
        reference_output = example["output"]
        generated_output = generate_output(**generation_params)
        writer.writerow({
            "instruction":instruction,
            "reference_output":reference_output,
            "generated_output":generated_output
        })

Fixing Generated Code

The book covers how to fine tune a GPT model and then analyze the generated code using the ast library (abstract syntax tree). It also shows how to gather the code into one CSV file with the test instructions and reference solutions and how to run it. BUT one problem is that this generated code will not have Python indentation or newlines. This isn't the model's fault: the dataset stores every reference output on a single line, so the model learns to write flattened code too, and the reference outputs need restoring as well. For learning this is actually completely fine, you will only use individual prompts and then it's ok to add the indentation yourself to correct the code. But for production one of the metrics for code generation is correctness. The generated CSV file would be a good way to start this evaluation, but once the newlines are gone, the original indentation can't be recovered with certainty for every row. You can however use proxies for fixing most of the code and generating errors for code that does not work after auto indentation. The following script generated by Claude shows how to restore the indentation.

import ast
import io
import keyword
import tokenize

BLOCK_KW = {"class", "def", "for", "while", "if", "elif", "else",
            "try", "except", "finally", "with"}
# keywords that always begin a new statement when seen outside brackets
ALWAYS_START = {"class", "def", "for", "while", "with", "try", "return",
                "elif", "except", "finally"}
# keywords that may sit in the middle of a statement
INFIX_KW = {"in", "is", "and", "or", "not", "if", "else", "as", "import", "lambda"}
ENDS_EXPR_KW = {"True", "False", "None", "pass", "break", "continue"}
FSTRING_START = getattr(tokenize, "FSTRING_START", -1)
FSTRING_END = getattr(tokenize, "FSTRING_END", -1)
SKIP = {tokenize.NEWLINE, tokenize.NL, tokenize.INDENT, tokenize.DEDENT, tokenize.ENDMARKER}


def _tokens(flat):
    toks = []
    try:
        for t in tokenize.generate_tokens(io.StringIO(flat).readline):
            if t.type not in SKIP:
                toks.append(t)
    except (tokenize.TokenError, SyntaxError):
        pass  # for cases where code is truncated or broken
    return toks


def _ends_expr(t):
    if t.type in (tokenize.NUMBER, tokenize.STRING, FSTRING_END):
        return True
    if t.type == tokenize.NAME:
        return not keyword.iskeyword(t.string) or t.string in ENDS_EXPR_KW
    return t.string in (")", "]", "}")


def _starts_stmt(t):
    if t.type in (tokenize.NUMBER, tokenize.STRING, FSTRING_START):
        return True
    return t.type == tokenize.NAME and t.string not in INFIX_KW


def _if_is_statement(toks, i):
    """An `if` is a statement if a top-level ':' comes before any `else`."""
    depth = 0
    for t in toks[i + 1:]:
        if t.string in "([{" and t.type == tokenize.OP:
            depth += 1
        elif t.string in ")]}" and t.type == tokenize.OP:
            depth -= 1
        elif depth == 0 and t.string == "else":
            return False
        elif depth == 0 and t.string == ":":
            return True
    return True


def restore_layout(code: str) -> str:
    """Best-effort: put newlines/indentation back into whitespace-flattened code."""
    try:
        ast.parse(code)
        return code  # already fine, don't touch it
    except SyntaxError:
        pass

    flat = " ".join(code.split())
    toks = _tokens(flat)
    if not toks:
        return code

    # 1) split the token stream into statements
    stmts = []  # (first_idx, last_idx, is_block_header)
    start, depth, ternary, lambdas = 0, 0, 0, 0
    for i, t in enumerate(toks):
        s = t.string
        if depth == 0 and i > start:
            first, prev = toks[start].string, toks[i - 1]
            new = False
            if s in ALWAYS_START:
                new = True
            elif s == "from":
                new = first not in ("raise", "yield") and prev.string != "yield"
            elif s == "import":
                new = first != "from" or prev.string == "*"
            elif first == "from" and prev.string == "*":
                new = True
            elif s == "if":
                new = _if_is_statement(toks, i)
                if not new:
                    ternary += 1
            elif s == "else":
                if ternary:
                    ternary -= 1
                else:
                    new = True
            elif _ends_expr(prev) and _starts_stmt(t):
                new = True
            if new:
                stmts.append((start, i - 1, False))
                start, ternary, lambdas = i, 0, 0

        if t.type == FSTRING_START or (t.type == tokenize.OP and s in "([{"):
            depth += 1
        elif t.type == FSTRING_END or (t.type == tokenize.OP and s in ")]}"):
            depth = max(0, depth - 1)
        elif depth == 0 and s == "lambda":
            lambdas += 1
        elif depth == 0 and s == ":":
            if lambdas:
                lambdas -= 1
            elif toks[start].string in BLOCK_KW:
                stmts.append((start, i, True))
                start, ternary = i + 1, 0
    if start < len(toks):
        stmts.append((start, len(toks) - 1, False))

    # 2) re-indent
    lines, indent, seen_class = [], 0, False
    for n, (a, b, header) in enumerate(stmts):
        first = toks[a].string
        if first == "class":
            indent, seen_class = 0, True
        elif first == "def":
            indent = 1 if seen_class else 0
        elif first in ("elif", "else", "except", "finally"):
            indent = max(0, indent - 1)
        end = len(flat) if n == len(stmts) - 1 else toks[b].end[1]
        lines.append("    " * indent + flat[toks[a].start[1]:end].rstrip())
        if header:
            indent += 1
    return "\n".join(lines) + "\n"

You can then apply the restore_layout function to the code generated by the book's GPT2 model or by a fine tuned SmolLM3 model. In the snippet below, it runs on both the reference and generated columns right after the CSV is loaded, and then the Manim analyzer runs on the corrected code.

import ast 
from pathlib import Path

import pandas as pd 

class ManimCodeAnalyzer(ast.NodeVisitor):
    def __init__(self):
        self.imports_manim = False
        self.scene_subclass_names = []
        self.play_calls = 0
        self.create_calls = 0
        self.errors = []

    def visit_Import(self, node):
        for alias in node.names:
            if alias.name == "manim":
                self.imports_manim = True
        self.generic_visit(node)

    def visit_ImportFrom(self, node):
        if node.module and node.module.startswith("manim"):
            self.imports_manim = True
        self.generic_visit(node)

    def visit_ClassDef(self, node):
        for base in node.bases:
            if isinstance(base, ast.Name) and base.id == "Scene":
                self.scene_subclass_names.append(node.name)
            elif isinstance(base, ast.Attribute):
                if base.attr == "Scene":
                    self.scene_subclass_names.append(node.name)
        self.generic_visit(node)

    def visit_Call(self, node):
        if isinstance(node.func, ast.Attribute):
            if (isinstance(node.func.value, ast.Name) and (node.func.value.id == "self") and (node.func.attr == "play")):
                self.play_calls += 1
        if isinstance(node.func, ast.Name) and node.func.id == "Create":
            self.create_calls += 1
        self.generic_visit(node)


def analyze_manim_code(code_str:str):
    try:
        tree = ast.parse(code_str)
    except SyntaxError as e:
        return {"syntax_valid":False, "syntax_error":str(e)}

    analyzer = ManimCodeAnalyzer()
    analyzer.visit(tree)
    return {
        "syntax_valid":True,
        "imports_manim":analyzer.imports_manim,
        "scene_subclass_names": analyzer.scene_subclass_names,
        "play_calls": analyzer.play_calls,
        "create_calls": analyzer.create_calls,
    }

output_path = Path("from_book","gpt2_manim_python_test_outputs.csv")
if output_path.exists():
    result_csv = pd.read_csv(output_path)
    result_csv['reference_output'] = result_csv['reference_output'].map(restore_layout)
    result_csv['generated_output'] = result_csv['generated_output'].map(restore_layout)
    result_csv['reference_output_analysis'] = result_csv['reference_output'].map(analyze_manim_code)
    result_csv['generated_output_analysis'] = result_csv['generated_output'].map(analyze_manim_code)

Then you can expand the analysis dicts into columns (for example with pd.json_normalize) and visualize the results with matplotlib. Based on the results you can add more epochs if there is enough room for improvement and then start to investigate more techniques which the book covers. In my runs, after 10 epochs following the hyper-parameter search, only 2 out of 50 test outputs from fine tuned GPT2 had valid syntax, while all 50 outputs from fine tuned SmolLM3 did.

Further Readings

Once you have a fine-tuned model that works you can move into more evaluations and other methods. The mentioned book does cover more improvements, but I found out that another book LLM Evaluation and Alignment by Han Lee, has more details around RLHF, policy optimization (also covered by the next part of the Smol course), and instruction following. This book is heavier on theory and goes somewhat chronologically in terms of evaluation improvements. It gives the names of the seminal papers that introduced evaluation concepts and why they started. Once you are satisfied with the training you can deploy the same model locally or you can use a remote device including small dedicated SBCs like Jetson Orin Nano (the newer version of the Jetson Nano). For that option you need to learn about quantization and memory issues which are covered in the Domain-Specific Small Language Models book.

large-language-modellocal llm

← All posts