I put together a list of things I want to learn, including retroactively some stuff I’ve already taught myself to get started. I’m currently about halfway through part 2, and keeping notes as I go; once I’m done (for whatever value of “done” that turns out to be) I may write this up as a resource for anyone else who wants to go on a similar journey.
- Use AI: Learn to communicate with hosted and locally running models, and integrate them into software.
- Modify AI: Learn how to provide models with external knowledge, fine-tune them, and serve adapted models.
- Build AI: Understand neural networks and transformers from the ground up, then build an artificial ant that learns through experience.
Part I — Using Existing Models
Goal: Understand how to access models, communicate with them programmatically, and choose where they run.
1. Hosted Models and APIs
- Create and configure an OpenRouter account.
- Understand the API request/response cycle.
- Make API calls from Python.
- Explore model names, providers, parameters, and response formats.
- Understand tokens, context windows, temperature, and token limits.
- Handle API errors, rate limits, and usage costs.
- Store API keys safely in a
.envfile. - Understand environment variables and why secrets should never go into source control.
- Understand the different categories of models available: generative, embedding, classification, reranking, vision-language, audio, and multimodal.
- Understand the distinction between a model’s architecture, training objective, and capabilities.
Project: Build a small Python command-line chat client that talks to OpenRouter.
2. Running Models Locally with Ollama
- Install Ollama and understand what it does.
- Understand the difference between a model and a model server.
- Download, list, run, and remove models.
- Communicate with Ollama through its API.
- Compare hosted and local models using the same prompts: quality, speed, privacy, hardware, and cost.
- Understand quantization: floating-point versus integer representations, and the tradeoffs among memory, speed, and model quality.
- Understand why different model sizes have different hardware requirements.
- Understand model formats such as GGUF and how they relate to quantization and model serving.
- Understand the distinction between model weights, model files, and the runtime serving them.
Project: Extend the chat client so you can switch between a hosted model and a local model without rewriting the application.
3. Structured Model Outputs
- Understand the difference between ordinary text responses and structured responses.
- Constrain model output to JSON.
- Define and provide a JSON Schema.
- Require specific fields, types, enums, and nested structures.
- Understand schema-constrained generation versus asking the model to “please return JSON.”
- Validate responses in Python.
- Handle malformed responses, missing fields, refusals, and API errors.
- Explore provider differences in structured-output support.
Project: Build an information-extraction tool that takes arbitrary text and returns validated JSON matching a schema you define.
4. Giving Models Tools
- Understand function calling (also called tool calling).
- Define a tool using a JSON Schema.
- Send tool definitions along with a model request.
- Understand the model’s tool-call response.
- Understand why the model requests a tool but your application—not the model—actually executes it.
- Execute the requested function in Python.
- Return the function’s result to the model.
- Build the tool-calling loop: model → tool → result → model.
- Give the model multiple tools and let it choose between them.
- Handle invalid arguments, tool errors, and unavailable tools.
Project: Build a model that can call Python functions to perform calculations, look up information, and manipulate data.
5. Designing an AI Application
- Understand the roles of system, developer, and user messages.
- Manage conversation history and context windows.
- Understand stateless API calls versus application-managed conversation state.
- Combine structured outputs and tool calling.
- Design multi-step workflows.
- Add guardrails and permission checks before executing consequential actions.
- Log requests, tool calls, results, latency, and token usage.
- Design a provider-independent interface that can work with both OpenRouter and Ollama.
Project: Build an agent harness with a loop that manages task state, tool execution, stopping limits, errors, approvals, and logs.
6. Model Behavior, Inference, and Generation
Goal: Understand what happens inside a model when it generates a response.
- Understand how a model generates text one token at a time.
- Explore greedy decoding and sampling.
- Understand probability distributions, conditional probability, and sampling.
- Understand temperature, top-k, and top-p.
- Explore deterministic versus nondeterministic responses, and why the same prompt can produce different answers.
- Understand expected values and why results vary between runs.
- Understand streaming responses and handling partial output.
- Explore stop sequences and maximum generation length.
- Experiment with generation parameters and compare outputs under the same conditions.
- Understand the relationship between probability distributions and the likelihood of different outputs.
- Compare repeated generations to measure output consistency.
- Understand semantic agreement versus exact textual agreement.
- Explore prompt sensitivity: how small changes in wording affect generated results.
- Understand why reproducibility is different from correctness.
Project: Build a small playground that lets you change generation parameters and compare the resulting outputs.
7. Security and Trust Boundaries
Goal: Understand the security implications of giving models access to tools, data, and external systems.
- Understand prompt injection and how it works.
- Distinguish trusted instructions from untrusted input.
- Understand why tool outputs and retrieved documents must be treated as untrusted.
- Limit tool permissions and validate arguments.
- Protect API keys, secrets, and sensitive data.
- Understand the principle of least privilege.
- Implement human approval for consequential actions.
- Explore common security mistakes in AI applications.
- Understand indirect prompt injection through retrieved documents and other external content.
Project: Add security controls to the AI assistant built in Section 5. Test it with malicious instructions and unexpected tool responses.
Part II — Modifying Existing Models
Goal: Understand how to take a pretrained model, give it access to new information, and adapt it to a particular task or body of material.
1. Retrieval-Augmented Generation (RAG)
Goal: Learn how to provide a model with relevant information at query time without changing its weights.
- Understand the difference between training a model and providing information at inference time.
- Understand embeddings: turning text into numerical representations.
- Generate embeddings for documents.
- Break documents into chunks.
- Store embeddings in a vector database.
- Perform similarity searches.
- Retrieve relevant passages in response to a question.
- Pass retrieved content into a model’s context.
- Understand chunk size, overlap, and retrieval quality.
- Evaluate whether retrieval actually improves answers.
- Explore limitations such as irrelevant retrieval, missing information, and context-window constraints.
- Choose RAG when the task needs information from a changing or external knowledge source, especially when answers should be grounded in retrieved passages.
- Choose fine-tuning when the goal is to change a model’s behavior, style, or response patterns—not simply to add a store of factual knowledge.
- Consider combining RAG and fine-tuning when an application needs both current or source-grounded information and a consistently adapted response style or task behavior.
- Compare the simplest suitable approach with alternatives using the same evaluation examples.
- Understand embedding similarity and common distance metrics.
- Compare semantic search with keyword search.
- Explore hybrid retrieval and reranking.
- Understand basic RAG variations, including query expansion, iterative retrieval, and agentic approaches.
- Evaluate retrieval quality separately from answer quality.
- Understand answer grounding, faithfulness, and the limitations of retrieved context.
Project: Build a local question-answering system over a collection of documents.
- Retrieve content within a specified date range.
- Filter by topic, source, or seFntiment.
- Ask questions about changes over time.
- Cite the underlying articles or posts supporting an answer.
2. Embeddings and Unsupervised Learning
Goal: Understand how embeddings can be used beyond similarity search.
- Understand clustering and implement K-means.
- Explore choosing K and evaluating cluster quality with silhouette scores.
- Compare discovered clusters against known categories using ARI or NMI.
- Explore stability by repeating clustering with different samples and random seeds.
- Explore density-based clustering with HDBSCAN.
- Investigate HDBSCAN’s parameter sensitivity.
- Evaluate stability by repeating HDBSCAN with different min_samples and min_cluster_size.
Project: Cluster passages from public-domain books and compare the results against their known sources.
3. Fine-Tuning Fundamentals
Goal: Understand how to change a pretrained model’s behavior through training.
- What does it mean to train a model?
- Pretraining versus fine-tuning.
- What are model weights, and what changes during training?
- What is supervised fine-tuning (SFT)?
- What is a training example?
- Understand prompts, completions, and labels.
- Preview epochs, batches, model size and depth, training duration, learning rates, gradient accumulation, optimizers, and learning-rate schedules; revisit these during the LoRA and Unsloth projects.
- Understand training versus validation performance, and what overfitting looks like.
- Preview regularization, dropout, weight decay, early stopping, and the effects of dataset size and diversity; revisit them during the neural-network and fine-tuning projects.
- Evaluate whether fine-tuning improved a model by using a held-out evaluation set and comparing it with a baseline.
- Preview transfer learning: how pretrained models reuse learned representations, when fine-tuning is appropriate, and its limitations; revisit it after the neural-network foundations.
- Understand the difference between teaching a model new behavior and giving it access to new information.
4. Supervised Learning: Text Classification
Goal: Practice the supervised-learning workflow with a small, interpretable model before fine-tuning a language model.
- Choose or create a small, separate text dataset with labeled categories; it need not be the content prepared for fine-tuning later.
- Split the data into training, validation, and test sets without allowing examples from one split to leak into another.
- Build a simple baseline, such as always predicting the most common category.
- Convert text into features with TF-IDF and train a logistic-regression classifier.
- Evaluate predictions with accuracy and per-class precision, recall, and F1; inspect a confusion matrix and misclassified examples.
- Compare the classifier with the baseline, and discuss what the test results do—and do not—show.
- Observe overfitting by comparing training and validation performance; try one small change and evaluate it without tuning against the test set.
Project: Build a sentiment classifier for a collection of dated articles or posts.
- Classify each item as positive, negative, or neutral.
- Use an existing pretrained sentiment model as a baseline.
- Train a simple TF-IDF + logistic regression classifier on labeled examples.
- Compare the two approaches using precision, recall, F1, and a confusion matrix.
- Investigate misclassifications, ambiguous language, sarcasm, and domain-specific sentiment.
5. Preparing Content for Training
Goal: Learn how to turn a collection of source material into a useful training dataset.
- Identify the goal of a training corpus.
- Extract content from your source.
- Clean HTML, boilerplate, duplicates, and irrelevant material.
- Preserve the original author’s voice rather than over-editing the material.
- Structure articles and metadata into a consistent corpus.
- Tokenize text and understand what tokens represent.
- Create training, validation, and test splits.
- Explore different training formats:
- Raw text for continued language-model training.
- Prompt/completion examples for instruction fine-tuning.
- Understand dataset quality checks, deduplication, and data provenance.
- Understand data contamination, train/test and evaluation leakage, and how to avoid them.
- Consider copyright, licensing, data ownership, and personal information.
- Recognize when a dataset is too small, unrepresentative, or has poor coverage.
- Measure dataset coverage and representativeness.
- Build a small corpus inspection and analysis tool.
Project: Produce a clean, documented, versioned dataset for the first fine-tune.
6. Your First Fine-Tune with Unsloth
Goal: Get a guided, end-to-end experience training an adapter before studying the underlying mechanics in detail.
- Understand what Unsloth does and how it relates to PyTorch, Transformers, PEFT, and TRL.
- Set up a supported training environment and choose a small model and dataset that fit available hardware.
- Load the model and a prepared dataset using a guided Unsloth workflow; treat the framework’s defaults as tools, not as concepts already mastered.
- Configure the basic training settings, such as the number of examples, batch size, learning rate, and training duration.
- Run a short adapter fine-tune and monitor training loss.
- Generate a few outputs before and after training using the same prompts and settings.
- Save the adapter and verify that it can be loaded again with its base model.
- Record the model, dataset, settings, hardware, and observed results; note questions about what the framework did behind the scenes.
Project: Complete a small guided fine-tune and produce a brief before-and-after comparison. The aim is to observe the workflow and outcomes, not yet to implement LoRA or explain every setting.
7. Unsloth: QLoRA and Deployment
Goal: Build on the first guided fine-tune by exploring a quantized adapter workflow, evaluating the result, and serving it.
- Revisit the earlier run and inspect its configuration, including adapter rank, target modules, dropout, and trainable parameter count; record questions to revisit during the LoRA section in Part III.
- Load a model using QLoRA and observe how quantized base weights and trainable adapter weights work together.
- Change one setting at a time, keep the dataset and evaluation prompts fixed, and compare the results with the earlier run.
- Track loss and evaluate generated outputs on held-out examples; recognize that lower training loss alone does not establish improved behavior.
- Save the adapter and its configuration, then reload it with the compatible base checkpoint.
- Understand adapter compatibility: architecture, base checkpoint, target modules, and format.
- Explore merging an adapter into the base model and the tradeoffs between merged and separate weights.
- Understand quantization and deployment formats, including memory, speed, and quality tradeoffs.
- Serve the adapted model through an inference interface; explore how Ollama can serve compatible adapters or converted models.
- Compare the base and adapted models using the same prompts and generation settings, and document limitations and results.
- Set random seeds where supported, compare multiple runs when resources allow, and keep datasets, code, model versions, and settings organized.
Project: Adapt the prepared content with QLoRA, evaluate the result against the unchanged base model, save and reload the adapter, and serve it locally where supported.
Part III — The Deep Magic
Goal: Understand how neural networks learn, how language models work internally, and how to build an agent that learns to survive and behave in a simulated world.
1. Foundations of Neural Networks
Goal: Understand the basic machinery behind modern machine learning.
- What is a neural network, conceptually?
- Tensors, vectors, matrices, and dimensions.
- Neurons, weights, biases, and activation functions.
- Forward propagation: turning inputs into outputs.
- Loss functions: measuring how wrong a prediction is.
- Backpropagation: figuring out which weights contributed to the error.
- Gradient descent and optimizers: changing weights to improve predictions.
- Training versus validation.
- Generalization versus memorization.
- Explore regularization techniques, dropout, weight decay, and early stopping.
- Build a tiny neural network in PyTorch, initially without a high-level training framework.
- Inspect weights, activations, predictions, loss, and learning behavior.
- Understand the common mathematical foundations shared by different neural-network architectures.
- Understand how different training objectives produce different model capabilities.
Project: Train a small neural network from random initialization and understand every major step in its training loop.
2. How Language Models Work: Tokenization, Attention, and Transformers
Goal: Understand the architecture behind modern large language models.
- Tokenization: converting text into token IDs.
- Embeddings: converting token IDs into vectors.
- Positional information: how a model represents token order.
- Attention: how tokens relate to other tokens.
- Self-attention and causal masking.
- Multi-head attention.
- Feed-forward layers and residual connections.
- Layer normalization.
- Understand the transformer block.
- How a transformer predicts the next token.
- How multiple transformer blocks form a language model.
- How the model turns predictions into generated text.
- Visualize attention and investigate what hidden layers represent.
- Examine why a model produced a particular output, while recognizing the limits of interpretability.
Project: Build a tiny character-level or token-level language model in PyTorch, then gradually implement a miniature transformer.
3. LoRA: Understanding the Machinery
Goal: Use your experience with Unsloth and the neural-network and transformer foundations to understand adapters, then implement a simplified LoRA layer yourself.
- Review linear layers: weight matrices, dimensions, and how a forward pass transforms inputs.
- Understand what full fine-tuning changes and why updating every model weight can be expensive in memory and compute.
- Understand parameter-efficient fine-tuning (PEFT): updating a small number of parameters while keeping the pretrained model mostly fixed.
- Build intuition for matrix rank and low-rank approximations.
- Understand the LoRA idea: represent a weight update as the product of two smaller trainable matrices instead of updating the full weight matrix.
- Follow the LoRA equation: for a layer with weight matrix (W \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}), use (W’ = W + \frac{\alpha}{r}BA), where (A \in \mathbb{R}^{r \times d_{\text{in}}}) and (B \in \mathbb{R}^{d_{\text{out}} \times r}); understand how the dimensions make the update valid.
- Understand the scaling factor, rank, and alpha, and how rank affects adapter size and capacity.
- Understand how initialization makes the adapter’s initial contribution small or zero, so adding it does not disrupt the pretrained model at the start of training.
- Keep the base weights frozen while gradients update only the adapter parameters.
- Trace a forward pass through a linear layer with a LoRA update, and verify that gradients reach the adapter but not the frozen base weights.
- Implement a LoRA-wrapped linear layer from scratch in PyTorch and test its dimensions, outputs, and gradients.
- Attach LoRA to selected layers of a small pretrained model; understand common target modules in attention and feed-forward layers.
- Explore how target-module choice, rank, scaling, and adapter dropout affect trainable parameter count and results.
- Prepare examples in the model’s expected chat or prompt/completion format, and understand how tokenization and labels determine which tokens contribute to the loss.
- Train the adapter with a minimal loop; track loss and watch for overfitting or unstable training.
- Compare the adapted model against the unchanged base model using the same held-out examples, prompts, and generation settings.
- Change one setting at a time, record results, and compare LoRA with full fine-tuning conceptually or on a small model when resources allow.
- Recognize LoRA’s limitations: it does not guarantee better results, depends on suitable data and configuration, and may be less effective when a task requires broad changes to the model.
Project: Implement a LoRA-wrapped linear layer, then adapt a small pretrained model with your simplified implementation. Compare it with the unchanged base model and the earlier Unsloth result using held-out examples and consistent generation settings.
4. Build an Ant World — The Training Harness
Before the ant gets a brain, it needs a world to live in.
Goal: Build a simulation environment in which an agent can act and learn.
- Represent a world as a two-dimensional grid.
- Define terrain: dirt, open space, food, water, and nest.
- Create the ant and define its position and state.
- Define actions: move, turn, dig, pick up, carry, and drop.
- Implement the simulation loop.
- Define what the ant can observe.
- Track time, energy, food, and other world state.
- Add reset and reproducible random world generation.
- Build a visual display so we can watch the simulation.
- Separate the world simulation from the agent’s decision-making code.
Project: A working ant simulation where a human can control the ant and inspect the world.
5. Give the Ant a Brain — The First Neural Network
Goal: Connect a neural network to the ant simulation.
- Translate the ant’s observations into numerical inputs.
- Decide what the network needs to see: position, nearby cells, food, nest, and so on.
- Define the network’s outputs: probabilities for each available action.
- Understand action selection and random exploration.
- Give the ant a reward signal.
- Record observations, actions, rewards, and outcomes.
- Understand the difference between supervised learning and reinforcement learning.
- Connect the neural network to the simulation.
- Experiment with an untrained network and observe its behavior.
Project: An ant controlled by a neural network, initially behaving randomly.
6. Reinforcement-Learning Fundamentals
Goal: Understand how an agent learns from experience rather than from labeled examples.
- Agents, environments, states, and actions.
- Rewards and cumulative rewards.
- The Markov decision process (MDP).
- Policies and value functions.
- Exploration versus exploitation.
- Discount factors and long-term rewards.
- Understand Q-learning as an introductory algorithm.
- Understand the difference between value-based and policy-based learning.
- Introduce policy-gradient learning.
- Understand PPO (Proximal Policy Optimization).
- Compare simple policy-gradient methods with PPO.
- Evaluate learning progress across multiple training runs.
- Understand probability distributions, expected values, mean, variance, and standard deviation when analyzing rewards and training results.
- Use correlation carefully; distinguish it from causation when interpreting experiments.
- Establish baselines, change one variable at a time, and record settings and results.
Project: Train an initial ant agent using a simple reinforcement-learning algorithm.
7. Make It Behave Like an Ant
Goal: Develop increasingly sophisticated behavior through learning, memory, and interaction.
- Improve the reward system and investigate unintended behavior.
- Introduce partial observation: the ant can only see a small area around itself.
- Add memory so it can use information from earlier observations.
- Introduce recurrent neural networks or other memory mechanisms.
- Introduce pheromone trails and their decay over time.
- Experiment with different ant roles and behaviors.
- Introduce multiple ants sharing the same world.
- Explore how simple individual rules can produce collective behavior.
- Experiment with obstacles, changing environments, and more complex goals.
- Visualize learning progress and compare different agents.
Project: A colony of artificial ants that develops useful foraging behavior through learning and interaction.
8. Build a Tiny Language Model from Scratch
Goal: Bring together neural-network foundations and transformer architecture to build a working language model without starting from pretrained weights.
- Prepare a small text corpus.
- Implement or choose a simple tokenizer.
- Convert text into training sequences.
- Create input/target pairs for next-token prediction.
- Build an embedding layer.
- Implement a simple neural language model.
- Understand n-gram language models.
- Understand how conditional probability determines the next-token distribution.
- Understand the relationship between n-gram models and Markov chains.
- Compare n-gram models with neural language models.
- Implement attention and a transformer block.
- Build the training loop.
- Train the model from random initialization.
- Monitor loss and inspect generated text.
- Build an evaluation set and compare model versions under the same conditions.
- Experiment with model size, context length, and training data; record settings and compare multiple runs.
- Explore why small models have limitations and how training data affects their behavior.
Project: Implement a bigram model. Extend it to trigram and higher-order models.
Project: Train a miniature language model from scratch and generate text with it.