Skip to content

YAML

YAML is a human-readable data serialization format used everywhere in the AI and DevOps world: configuration files, pipeline definitions, model metadata, and container orchestration. The syntax looks simple; the corner cases do not.

Quick Reference

Concept YAML style
Mapping key: value
List - item
String text or "text"
Number 42, 3.14
Boolean true, false, yes, no
Null null, ~, or empty
Multiline \| or >
Anchor &id
Alias *id

Why YAML Is Everywhere

YAML is popular because: - It is readable. - It supports nested structures cleanly. - It is widely supported in tooling. - It is used by many infrastructure and pipeline systems.

The downside is that "readable" does not always mean "simple." Whitespace, colons, quotes, and type inference can cause surprising results.

Basic Structure

A YAML document is a collection of mappings and sequences, optionally nested.

model:
  name: bert-base
  version: 1
  active: true

datasets:
  - name: train
    path: data/train.csv
  - name: validation
    path: data/val.csv

Indentation matters. Use spaces, not tabs.

Mappings

Mappings are key/value pairs.

model:
  name: my_model
  epoch: 10

Nested mappings:

training:
  optimizer:
    name: adam
    lr: 0.001

Keys can be plain or quoted:

"model.name": bert

Use quoted keys when the key contains characters that could be ambiguous.

Sequences

Sequences are lists.

tags:
  - nlp
  - transformers
  - embeddings

Nested sequences:

matrix:
  - [1, 0, 0]
  - [0, 1, 0]
  - [0, 0, 1]

Flow style is also valid, though block style is more common in config files:

tags: [nlp, transformers, embeddings]

Scalars

Strings

name: bert
description: "A model for text representation"

Quoting is often optional, but helpful when the value: - Starts with special characters - Contains colons or hashes in a way that could confuse parsing - Looks like a number or boolean - Has leading or trailing whitespace you want to preserve

pattern: "0.5"
note: "true is a string here"

Numbers

epoch: 10
lr: 0.001
layers: 12

YAML infers numeric types. That is convenient but can surprise you when a value like 0.5 or 123 is parsed as a number instead of a string.

Booleans

active: true
debug: false

Be careful: true, false, yes, no, on, off can all be interpreted as booleans in some YAML parsers. If you mean a string, quote it.

Null

fallback: null
alias: ~
empty_field:

Empty values and explicit null or ~ represent nulls.

Multiline Strings

Two common block scalar styles:

Literal block |

Preserves newlines.

prompt: |
  You are a helpful assistant.
  Answer concisely.

Folded block >

Folds newlines into spaces by default.

description: >
  This is a long description
  that becomes one line
  after folding.

Chomping indicators modify trailing newlines:

  • | — keep trailing newline
  • |- — strip trailing newline
  • |+ — keep extra trailing newlines

For most config use, | is the safest default when you want a block of text to stay readable.

Indentation

Rules: - Use spaces. - Be consistent within a file. - Nested structures are indented relative to their parent. - A mapping or sequence entry is usually followed by either a value or a deeper block.

model:
  name: bert
  params:
    layers: 12
    hidden: 768

Bad indentation is one of the most common YAML errors. The parser does not always guess what you meant.

Comments

# This is a comment
model: bert  # inline comment

Comments are ignored by the parser.

Anchors and Aliases

Anchors let you reuse a node.

defaults: &defaults
  optimizer: adam
  lr: 0.001

experiment_a:
  <<: *defaults
  lr: 0.0005

experiment_b:
  <<: *defaults
  optimizer: sgd

This is useful in configuration files where several sections share a base.

Be careful: - Anchors are file-scoped. - Aliases reference the anchored node. - Not every tool or viewer handles them well in all contexts.

Type Ambiguity

YAML guesses types. This is the most common source of "it looks right but means something else."

Examples that can misparse: - 0.5 as a number - true as a boolean - 123 as an integer - 1e3 as a float

If the value should be a string, quote it.

version: "1.0"
id: "001"
yes_no: "true"

When in doubt, quote values that should preserve their textual form.

Common Patterns in Data/ML Workflows

Model config

model:
  name: resnet50
  pretrained: true
  input_size: [3, 224, 224]
  dropout: 0.2

training:
  batch_size: 64
  epochs: 20
  lr: 0.001
  mixed_precision: true

Pipeline steps

pipeline:
  - load
  - clean
  - tokenize
  - embed
  - classify

Hyperparameter sweep

sweep:
  method: grid
  parameters:
    lr:
      values: [0.01, 0.001, 0.0001]
    batch_size:
      values: [32, 64]

Metadata

dataset:
  name: reviews
  language: en
  size: 50000
  split:
    train: 0.8
    val: 0.1
    test: 0.1

Parsing in Python

With PyYAML:

import yaml

with open("config.yaml") as f:
    config = yaml.safe_load(f)

model_name = config["model"]["name"]

Prefer safe_load when possible. Avoid load on untrusted input.

With a more modern parser:

from pathlib import Path
import yaml

config = yaml.safe_load(Path("config.yaml").read_text())

For writing:

with open("out.yaml", "w") as f:
    yaml.safe_dump(config, f, sort_keys=False)

Common Gotchas

  • Tabs are usually not allowed for indentation.
  • Colons need a space after them in mappings.
  • A value like true may not be the string you wanted.
  • Indentation errors can change structure silently or fail in non-obvious ways.
  • Quotes matter when a value might be interpreted as a number, boolean, or special token.
  • Anchors and aliases are powerful but can make files harder to read and diff.
  • Mixing flow style and block style can make the structure harder to follow.

Validation Mindset

Treat YAML as data, not as freeform notes: - Check keys and types after loading. - Validate required fields. - Watch for values that parsed as the wrong type. - Keep config structures stable across versions. - Prefer explicit quoting for fields where the exact string matters.

  • toml — a less indentation-sensitive config format
  • python-dotenv — env-based configuration
  • make — running YAML-driven workflows from the command line
  • curl — testing services that may consume YAML payload or config
  • ssh — deploying YAML configs to remote systems

Official Documentation

  • YAML specification and grammar references
  • Your parser's documentation, e.g. PyYAML or the YAML library you use
  • Tool-specific YAML schemas when they exist

YAML is a practical format, but the practical habit is to treat it as structured data and verify what you actually parsed.

Last Updated

2026-09-06 — Initial version.