End-to-end transformer fine-tuning
local graph
Chapter 3 — End-to-end transformer fine-tuning
Section titled “Chapter 3 — End-to-end transformer fine-tuning”This chapter covers
- Specializing a very small language model to generate working Manim code
- The hyperparameter tuning process in transformer fine-tuning
- Evaluating the quality of the generated code
This chapter walks through an end-to-end example of fine-tuning a small model (GPT-2 small) for a specific task. This approach will apply to fine-tuning any GPT-like model for generative tasks.
3.1 Data preparation
Section titled “3.1 Data preparation”In this chapter, we’ll fine-tune the GPT-2 small model (https://huggingface.co/openai-community/gpt2) to generate working Manim code from natural-language prompts. Manim (https://github.com/ManimCommunity/manim) is an open source Python animation engine for explanatory math videos—it creates precise animations programmatically. Figure 3.1 shows an example of Manim code and its rendering.
Example: LaTeXMathFonts
from manim import *
class LaTeXMathFonts(Scene): def construct(self): tex = Tex( r"$x^2 + y^2 = z^2$", tex_template=TexFontTemplates.french_cursive, font_size=144, ) self.add(tex)Figure 3.1 An example of Manim code (bottom) and the corresponding rendering (top)
I chose GPT-2 small as a baseline not only because it can’t produce Manim code, but also to show that you can start with a small model and a high-quality, domain-specific dataset—even a relatively small one—and still specialize it for a task and achieve good performance. A companion Colab notebook contains the full source code from this chapter. Hardware acceleration (GPU, free tier) is required.
We’ll use the manim_python dataset from the Hugging Face Hub (https://huggingface.co/datasets/Edoh/manim_python). It has two fields: instruction (a natural-language prompt) and output (the corresponding Manim Python code). The dataset includes two splits: train (599 samples) and test (51 samples).
We’ll use the Hugging Face Datasets library (introduced in chapter 2) to handle the dataset. First, we need to download it:
from datasets import load_dataset
dataset = load_dataset("Edoh/manim_python")The following snippet shows one of the samples in the training split:
{'instruction': "Create a new scene named 'MyScene'.", 'output': 'frommanim import * class MyScene(Scene): def construct(self): pass'}
Next, we'll load the model tokenizer:
from transformers import GPT2Tokenizer
model_name = "openai-community/gpt2"tokenizer = GPT2Tokenizer.from_pretrained(model_name)tokenizer.pad_token = tokenizer.eos_tokenThe dataset isn’t ready for fine-tuning and testing the model, so we’ll implement a custom preprocessing function:
def preprocess_data(examples): inputs = [ f"Instruction: {instr}\nOutput: {out}" for instr, out in zip(examples["instruction"], examples["output"]) ]
tokenized = tokenizer(inputs, truncation=True, max_length=512, padding="max_length")
tokenized["labels"] = tokenized["input_ids"].copy() return tokenizedThe preprocess_data function concatenates the instruction and output columns and then tokenizes the result. It’s applied to every sample in the dataset (both train and test splits):
tokenized_datasets = dataset.map(preprocess_data, batched=True, remove_columns=dataset["train"].column_names)The original columns are deleted because they’re no longer needed. The data is now ready, and we can prepare the model for training.
3.2 Fine-tuning
Section titled “3.2 Fine-tuning”To fine-tune the model, we’ll use Hugging Face’s Transformers library, introduced in chapter 2, along with Optuna (https://optuna.org/) for hyperparameter search. This process involves systematically exploring the most suitable set of hyperparameters that can elevate the performance of a model. Hyperparameters, distinct from model parameters, aren’t inherently learned during the training phase. Instead, they’re predetermined. Their precise configuration can profoundly influence a model’s performance, bridging the gap between an average model and one that excels. Optuna is an ML framework-agnostic, open source Python library for automatic hyperparameter tuning. It lets you search for optimal hyperparameters using standard Python conditionals, loops, and syntax. Because Optuna is fully supported by Hugging Face libraries, we’ll use it as the search backend without working directly with its API.
We’ll define a custom function, model_init, for hyperparameter search so each trial starts with a freshly initialized model:
from transformers import GPT2LMHeadModel
def model_init(): return GPT2LMHeadModel.from_pretrained(model_name, device_map='auto')Next, we’ll configure the training arguments before starting the hyperparameter search:
from transformers import TrainingArguments
training_args = TrainingArguments( output_dir="./gpt2-manim-python-finetuned", eval_strategy="epoch", save_strategy="epoch", logging_strategy="steps", logging_steps=100, save_total_limit=2, load_best_model_at_end=True, metric_for_best_model="eval_loss", greater_is_better=False, fp16=True, report_to="none",)In the previous code snippet, we did the following:
- Specified the path to the root directory for saving checkpoint candidates
- Chose epoch as the evaluation and saving strategies
- Chose steps as the logging strategy (metrics reported every 100 steps)
- Set the maximum number of checkpoint savings per single trial
- Chose evaluation accuracy as the key metric for choosing the best model
- Enabled mixed precision training (FP16)
Because we have set an evaluation strategy, we’ll use some of the training data for evaluation. We’ll split the training set and reserve 10% of the samples for evaluation:
train_val_split = tokenized_datasets["train"].train_test_split(test_size=0.1)tokenized_datasets["train"] = train_val_split["train"]tokenized_datasets["validation"] = train_val_split["test"]We can now initialize the Trainer with the training arguments and the tokenized training and evaluation data:
from transformers import ( Trainer, DataCollatorForLanguageModeling, EarlyStoppingCallback)
data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
trainer = Trainer( model_init=model_init, args=training_args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["validation"], tokenizer=tokenizer, data_collator=data_collator, callbacks=[EarlyStoppingCallback(early_stopping_patience=2)],)We have also added a callback to stop a training trial if it doesn’t improve for two consecutive steps.
We’ll define the search space for hyperparameter tuning as follows:
def hp_space(trial): return { "learning_rate": trial.suggest_float("learning_rate", 1e-5, 5e-4, log=True), "per_device_train_batch_size": trial.suggest_categorical("per_device_train_batch_size", [2, 4, 8]), "weight_decay": trial.suggest_float("weight_decay", 0.0, 0.3), "num_train_epochs": trial.suggest_int("num_train_epochs", 3, 6), "warmup_steps": trial.suggest_int("warmup_steps", 0, 500), "gradient_accumulation_steps": trial.suggest_categorical("gradient_accumulation_steps", [1, 2, 4]), }We’ve defined a function that takes a trial object as input, which Optuna will use to sample hyperparameter values. In the body of the hp_space function, we specify value ranges to define the search space. The hyperparameters are the learning rate, batch size per device, weight decay, number of training epochs, warmup steps, and gradient accumulation steps. Some ranges were chosen to fit the computational power available in the free-tier Colab VM (a single NVIDIA Tesla T4). In other hardware settings, some hyperparameters (such as batch size or gradient accumulation steps) may need different values or ranges.
NOTE Gradient accumulation steps are the number of mini-batches over which gradients are accumulated before the model’s weights are updated. This enables a larger effective batch size without exceeding GPU memory limits, which is especially useful when GPU memory is scarce.
We’re now ready to run the hyperparameter search. Here we’ll specify the backend engine (Optuna in this example), the number of trials, and the metric used to compare trials (evaluation loss in this case):
best_run = trainer.hyperparameter_search( direction="minimize", backend="optuna", n_trials=10, hp_space=hp_space, compute_objective=lambda metrics: metrics["eval_loss"],)Once the search is complete, we can configure the trainer with the best hyperparameters, stored in the best_run variable:
for key, value in best_run.hyperparameters.items(): setattr(training_args, key, value)
trainer = Trainer( model_init=model_init, args=training_args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets.get("validation"), tokenizer=tokenizer, data_collator=data_collator, callbacks=[EarlyStoppingCallback(early_stopping_patience=2)],)Finally, we can start tuning the model:
trainer.train()After training, we’ll save the fine-tuned model and tokenizer to disk so we can reload them for testing or to generate Manim code:
trainer.save_model("./gpt2-manim-python-finetuned")tokenizer.save_pretrained("./gpt2-manim-python-finetuned")Next, we’ll look at testing the model.
3.3 Testing the fine-tuned model
Section titled “3.3 Testing the fine-tuned model”To test the fine-tuned model on the test set, we’ll first load it from disk into GPU memory:
import torch
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()Next, we’ll define a custom function, generate_output, that we’ll run on each prompt (the instruction column) in the test dataset to generate the expected Manim code (the output column is our ground truth). The function takes a prompt as its first argument , along with the maximum generation length and optional parameters such as temperature and decoding strategy (beam search and nucleus sampling in this case):
def generate_output(instruction, max_length=150, num_beams=5, temperature=0.7, top_p=0.9, repetition_penalty=1.2):After the prompt has been tokenized
prompt = f"Instruction: {instruction}\nOutput:"input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)the generation of Manim code from the input text happens:
generated_ids = model.generate( input_ids, max_length=max_length, num_beams=num_beams, temperature=temperature, top_p=top_p, repetition_penalty=repetition_penalty, do_sample=True, pad_token_id=tokenizer.eos_token_id, eos_token_id=tokenizer.eos_token_id, early_stopping=True, no_repeat_ngram_size=2,)The generated tokens are decoded, skipping the special ones:
generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)Finally, the generated text is returned to the caller:
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_textWe’ll persist the test results to a CSV file to make them easier to analyze later:
import csv
output_csv = "gpt2_manim_python_test_outputs.csv"with open(output_csv, mode="w", newline="", encoding="utf-8") as csvfile: writer = csv.DictWriter(csvfile, fieldnames=["instruction", "reference_output", "generated_output"]) writer.writeheader()We’ll iterate over the test samples, calling the generate_output function to generate Manim code for each instruction, and we’ll append the results—along with the prompt and ground truth—to the CSV file:
for example in dataset['test']: instruction = example["instruction"] reference_output = example["output"]
generated_output = generate_output(instruction)
writer.writerow({ "instruction": instruction, "reference_output": reference_output, "generated_output": generated_output, })Let’s analyze some meaningful examples generated by the fine-tuned model at test time after a two-trial hyperparameter search and fine-tuning, conducted as described earlier.
Given the following prompt
GI Scale the triangle by a factor of 2 in 2 seconds.
the following Manim code was generated:
from manim import *
class MyScene(Scene): def construct(self): triangle = RegularPolygon(n=3, radius=2, color=YELLOW) self.add(triangle) self.play(triangle.animate.scale(2), run_time=2) rectangle.move_to((UP * 1.5))The preceding code is correct, except for the last line. Remove it, and the code runs as the prompt specifies: it creates a Manim scene, adds a triangle, and doubles the triangle’s size over 2 seconds.
Let’s look at another example. Consider the following prompt:
GI Create a point at coordinates (0, 0) and color it pink.
The following Manim code was generated:
from manim import *
class MyScene(Scene): def construct(self): point = Point(width=4, height=2) color=PINK) self.add(point)The preceding code runs and meets the prompt’s requirements, except that the point is placed at (4, 2) instead of the required (0, 0). Across multiple tests in this experiment, the fine-tuned model often struggles to set numeric arguments for Manim objects.
In this experiment, the overall hallucination rate is low and is mostly limited to the two situations just described. We could reduce (if not eliminate) these by running more hyperparameter-search trials (at least 3; 5 is probably best for the manim_python dataset), trying different sampling strategies, reducing the maximum number of generated tokens, or both. Even so, this example shows that a small model trained on a curated, domain-specific dataset can quickly gain expertise in a given domain or task.
3.4 Domain-specific evaluation
Section titled “3.4 Domain-specific evaluation”Many statistical metrics can evaluate a language model’s performance at test time. These metrics provide useful insights for general-domain tasks, especially those based only on unstructured natural language. But when benchmarking on a specific domain—whether the model is large, small, or fine-tuned—and the outputs diverge from human language, you’ll still need a qualitative review by subject matter experts (SMEs) and sometimes also external strategies and tools. Building on the fine-tuned model for the Manim dataset we’ve discussed in this chapter, we’ll look at downstream strategies to automate the evaluation of the generated code and reduce the burden on SMEs.
In this case, a complete evaluation pipeline could include the following automated steps:
- Syntax checking—The generated content is Python code, so we must ensure it’s syntactically valid.
- Static analysis for Manim API usage—Parse the generated code to check for expected Manim classes, methods, or function calls.
- After checking that the generated Manim code is syntactically valid, we need to verify that its execution completes as expected.
- Optional—Verify the rendering’s correctness (because Manim output is always an image or an animation).
You can implement syntax checking with a custom function using Python’s built-in ast package :
import ast
def is_syntax_valid(code_str): try: ast.parse(code_str) return True, "" except SyntaxError as e: return False, str(e)NOTE Python’s ast package (Abstract Syntax Trees, https://docs.python .org/3/library/ast.html) lets you work with Python’s abstract syntax trees. We’ll cover it in chapter 7 in the context of Python code generation with SLMs.
The is_syntax_valid function calls ast.parse and returns True if the generated code is valid Python syntax, and False otherwise. It checks only syntax, not whether the code uses a specific API, but it’s a useful first step to catch invalid model responses before running more complex checks.
The next step is static analysis for the Manim API. It will still use ast, but it will be tailored to the package being tested. To do that, we can create a dedicated class that extends the ast module’s NodeVisitor:
from ast import NodeVisitor
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 = []This class includes several utility functions that override the parent class’s visit method and must be named with the visit_ prefix. The first verifies whether the Manim package is imported directly in the generated code:
def visit_Import(self, node): for alias in node.names: if alias.name == "manim": self.imports_manim = True self.generic_visit(node)Another function will check whether Manim elements are imported via from … import:
def visit_ImportFrom(self, node): if node.module and node.module.startswith("manim"): self.imports_manim = True self.generic_visit(node)Manim programs are usually defined as a Scene class (or subclass). It’s useful to add a function that checks whether a generated class is a Scene or a subclass of Scene:
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)Finally, we need a function that counts calls to the play method in our Scene subclass and Manim Create initializations:
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)Now we can define a function that uses the ManimCodeAnalyzer class:
def analyze_manim_code(code_str): analyzer = ManimCodeAnalyzer()analyze_manim_code first checks the input code’s Python syntax:
try: tree = ast.parse(code_str)except SyntaxError as e: return { "syntax_valid": False, "syntax_error": str(e), "imports_manim": False, "scene_subclass_names": [], "play_calls": 0, "create_calls": 0, }If the Python code isn’t valid, execution stops, and the function returns insights about any issues found. If the code is valid, the function uses the custom analyzer to parse it for the Manim API:
analyzer.visit(tree)Finally, it returns a summary of the executed static analysis:
return { "syntax_valid": True, "syntax_error": None, "imports_manim": analyzer.imports_manim, "scene_subclass_names": analyzer.scene_subclass_names, "play_calls": analyzer.play_calls, "create_calls": analyzer.create_calls,}As an example of how this works, given the following input Manim code snippet
from manim import *
class MyScene(Scene): def construct(self): circle = Circle() self.play(Create(circle))the analyze_manim_code function returns the following:
syntax_valid: Truesyntax_error: Noneimports_manim: Truescene_subclass_names: ['MyScene']play_calls: 1create_calls: 1Executing the generated code can follow a workflow like this:
- Save the generated code to a .py file.
- Run the Manim CLI to render the scene.
- Check whether the rendering succeeds.
You could implement this by defining a custom function that covers all three of these steps. The function will take the generated Manim code snippet and the name of the Scene class as inputs:
def evaluate_manim_code(code_str, scene_class_name="CustomScene"):First, the input Manim code (code_str) is saved to a file:
import osimport tempfile
with tempfile.TemporaryDirectory() as tmpdir: code_path = os.path.join(tmpdir, "generated_scene.py") with open(code_path, "w") as f: f.write(code_str)Next, the command to run the Manim CLI is set:
cmd = [ "manim", "-ql", code_path, scene_class_name,]It executes the Python file to render the scene:
import subprocess
try: result = subprocess.run(cmd, capture_output=True, text=True, timeout=60) success = result.returncode == 0 output = result.stdout + "\n" + result.stderrexcept subprocess.TimeoutExpired: success = False output = "Timeout expired during rendering."In the CLI configuration, we used the -ql (quality low) option to reduce the computational burden and speed up the test.
Next, using the same Manim snippet from the syntax-checking step, validate that the generated code runs correctly.
generated_code = """from manim import *
class MyScene(Scene): def construct(self): circle = Circle() self.play(Create(circle))"""We use evaluate_manim_code to validate that the generated Manim snippet runs correctly. This code
success, output = evaluate_manim_code(generated_code, scene_class_name="MyScene")print("Render success:", success)print("Output:", output)produces output like the following:
Render success: TrueOutput: Manim Community v0.19.0[08/04/25 14:03:42] INFO Animation 0 : Using cachedcairo_renderer.py:89data (hash :1185818338_3789429803_223132457)INFOscene_file_writer.py:739INFOscene_file_writer.py:886File ready at'/content/media/videos/generated_scene/480p15/MyScene.mp4'INFOscene.py:255Played 1 animationsRunning evaluate_manim_code also saves the generated scene or animation as a local MP4 file. If your test dataset includes reference videos or images, you can extract frames or thumbnails, compute similarity metrics such as SSIM or LPIPS between the generated and reference images, and compare them against quality thresholds. This validation is out of scope for this chapter, but you can implement it by checking these metrics against your chosen thresholds.
NOTE The structural similarity index measure (SSIM) predicts the perceived quality of digital TV, cinematic images, and other digital images and videos. It also measures similarity between two images. The scikit-image Python image-processing package (https://scikit-image.org/) provides a ready-to-use implementation. Learned Perceptual Image Patch Similarity (LPIPS) is a perceptual similarity metric that uses deep-network activations to measure the distance between image patches. It can also serve as a perceptual loss for image optimization.
Here are some final recommendations for validating execution and rendering correctnessin tasks like these:
- Sandboxing—Running arbitrary generated code is risky. Use sandboxing tools (forexample, Docker containers or restricted environments) to isolate execution.- Timeouts—Set timeouts to prevent hangs or infinite loops.- Resource limits—Limit CPU, GPU, and memory usage during rendering to savetime and money.That completes our introduction to tuning SLMs for specific domains and tasks. In the next chapter, we’ll shift our focus to the book’s core topics: SLM optimization, compression , and deployment in hardware-constrained environments.
Summary
Section titled “Summary”- GPT-2 small models can be fine-tuned for domain-specific tasks with datasets of a few hundred samples.
- Manim is a Python animation engine for creating mathematical visualizations with code.
- Before tokenizing for language model training, concatenate the instruction and output fields during preprocessing.
- Optuna automates hyperparameter searches and integrates with the Hugging Face Transformers library.
- Model initialization functions create a fresh model instance for each hyperparameter trial during search.
- Training arguments set evaluation strategies, logging intervals, checkpoint saving, and mixed-precision training.
- Early stopping callbacks prevent overfitting by stopping training when the validation loss stops improving.
- Hyperparameter search spaces define ranges for the learning rate, batch size, weight decay, number of epochs, and other parameters.
- You can use Python’s ast module to validate generated code syntax.
- Static analysis verifies domain-specific API usage patterns in generated code.
- Custom NodeVisitor classes extend ast functionality to analyze framework-specific code structures.
- Execution testing runs generated code via command-line tools to verify functional correctness.
- Rendering validation compares generated outputs to reference images via similarity metrics.
- Sandboxing and timeouts improve safety when running generated code automatically.
- Small language models perform well on specialized tasks with curated domain-specific datasets.
- Automated evaluation pipelines reduce the burden on subject matter experts assessing code quality.