Back to blog

    Building an LLM Fine-Tuning Pipeline with Dagster

    DagsterMLOpsLLMData Engineering

    Why Dagster for ML Pipelines?

    Most ML training scripts are monolithic: one long script that downloads data, cleans it, tokenizes, and trains. This works until it doesn't — a failed training run means re-downloading and re-processing everything. For recipe-lm, I wanted something better.

    Dagster's asset-based approach was a natural fit. Instead of defining a sequence of tasks, you define the data artifacts you want to produce. Each asset declares its dependencies, and Dagster figures out the execution order, caching, and lineage tracking.

    The Pipeline at a Glance

    The recipe-lm pipeline fine-tunes Google's Gemma-2B on recipe data using LoRA, producing a lightweight adapter that can generate recipes from short prompts. The full DAG has five assets:

    raw_dataset → cleaned_dataset → tokenized_dataset → train_val_splits → trained_model
    

    Each asset is independently materializable — if my cleaning logic changes, I don't need to re-download 5,000 recipes from Hugging Face.

    Data Processing: The Messy Middle

    Downloading and Sampling

    The pipeline starts by pulling from the corbt/all-recipes dataset on Hugging Face Hub (~185K recipes). I downsample to 5,000 examples for tractability:

    @asset(group_name="data_processing")
    def raw_dataset(hf_config: HuggingFaceConfig) -> Dataset:
        ds = load_dataset(hf_config.dataset_name, split="train")
        return ds.shuffle(seed=hf_config.seed).select(range(hf_config.max_samples))
    

    Cleaning Recipe Data

    Recipe datasets are notoriously noisy. Recipes scraped from the web come with trailing commentary — attribution lines, social media plugs, personal anecdotes. I built a regex-based cleaning step that strips 18 categories of trailing noise:

    TRAILING_PATTERNS = [
        r"Submitted by.*$",
        r"Recipe from.*$",
        r"Follow us on.*$",
        r"Notes:.*$",
        # ... 14 more patterns
    ]
    

    This step also deduplicates exact matches and filters empty rows. On a typical run, it removes about 15% of the data — messy, but important for training quality.

    Tokenization

    The cleaned text gets tokenized with Gemma's SentencePiece tokenizer, truncated to 512 tokens, and padded to uniform length. One subtle detail: Gemma doesn't define a pad token by default, so the pipeline falls back to using the EOS token.

    Training: LoRA on Any Hardware

    The most interesting architectural decision was making training hardware-agnostic. The trained_model asset auto-detects the available device and adjusts its strategy:

    HardwareStrategyMemory
    CUDA GPUQLoRA (4-bit NF4 quantization)~8 GB
    Apple Silicon (MPS)Full LoRA, float32~13 GB
    CPUFull LoRA, float32~13 GB

    LoRA keeps training efficient by only updating ~2-5% of the model's parameters. The adapter that comes out the other end is just 67 MB — compared to 5 GB for the full model weights.

    Tracking What Matters

    The training asset returns a MaterializeResult with metadata that Dagster surfaces in its UI:

    return MaterializeResult(metadata={
        "train_loss": train_loss,
        "val_loss": val_loss,
        "val_perplexity": math.exp(val_loss),
        "trainable_params": trainable_params,
        "adapter_path": str(adapter_path),
    })
    

    No separate experiment tracking tool needed — Dagster's built-in metadata and run history handles it.

    Configuration as a Resource

    All pipeline parameters live in a single ConfigurableResource:

    class HuggingFaceConfig(ConfigurableResource):
        dataset_name: str = "corbt/all-recipes"
        model_name: str = "google/gemma-2b"
        max_samples: int = 5000
        max_seq_length: int = 512
        lora_r: int = 8
        lora_alpha: int = 16
        num_train_epochs: int = 3
        learning_rate: float = 2e-4
    

    This means I can tweak hyperparameters from the Dagster UI, override them via YAML, or pass them programmatically — without touching asset code.

    From Training to Serving

    The pipeline produces a LoRA adapter, but production inference needs something leaner. A separate conversion step merges the adapter into the base model and quantizes it to GGUF Q4_K_M format (~2.3 GB). This runs on CPU via llama-cpp-python, making it deployable on free-tier Hugging Face Spaces.

    The serving layer (FastAPI + SSE streaming) consumes the GGUF model and exposes a /generate endpoint that streams tokens to a React frontend and a voice agent.

    What I'd Do Differently

    1. Add a data validation asset. Right now, data quality checks are embedded in the cleaning step. A dedicated validation asset with Great Expectations or Pandera would make issues more visible.
    2. Partition by dataset version. Dagster partitions would let me track which model was trained on which data snapshot.
    3. Integrate experiment tracking. Dagster metadata is good for pipeline observability, but for serious hyperparameter search, I'd add Weights & Biases.

    Conclusion

    Dagster turned what would have been a fragile training script into something I can iterate on with confidence. The asset model maps naturally to ML workflows — each stage produces a concrete artifact, and the dependency graph makes it easy to re-run only what changed. If you're building ML pipelines that need to be reproducible and observable, it's worth a look.