Machine Learning Guide

Machine Learning Guide

Download on the App Store

All Machine Learning Guide episodes

  • MLA 030 AI and Programming Jobs in 2026

    AI and programming jobs in 2026: unemployment held and software postings are recovering, but entry-level hiring narrowed and the growth went senior. Why cheap code made specs, verification and domain knowledge scarce, where AI jobs grew, and what to learn and show.

    Links
    • Notes and resources at ocdevel.com/mlg/mla-30
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    Will AI replace programmers?

    Not in aggregate so far. US unemployment was 4.1% in October 2026, in a 4.1–4.3% range since March. What changed is who gets hired. Stanford's Canaries in the Coal Mine (August 2026, ADP payroll data through June) puts 22–25 year olds in the most AI-exposed occupations 19% below less-exposed peers, up from 15% a year earlier. The gap comes from reduced hiring, not layoffs, concentrates where AI automates the task, and holds when tech firms and computer occupations are excluded. The authors call it descriptive, not causal.

    Are software jobs coming back?

    Postings are, at the senior end. Indeed's software development index (Feb 2020 = 100):

    ~234 (Mar 2022) → ~61 (May 2025) → ~81 (Nov 2026)

    That's +24% year over year and still 19% below pre-pandemic, while all postings are about 4% above. 71% of the 2025–26 increase came from senior roles and 37% from AI-titled jobs.

    Is it harder to get a first job in software?

    Yes. In Q1 2026, Indeed classed 69% of software postings as senior and 4.5% as entry-level. SignalFire puts new-grad hiring at 12 big tech companies down about 65% from 2019. In the New York Fed's 2024 data by major:

    Recent grads Unemployment Underemployment Early-career median pay Computer engineering 7.8% 15.8% $90,000 Computer science 7.0% 19.1% $87,000 All majors 4.2% 39.4% $58,000 How many layoffs are because of AI?

    About a fifth of announced US cuts in 2026: 121,401 through October, per Challenger, Gray & Christmas. AI led as a stated reason through the summer, then fell to 1,265 in October. Total cuts are down 44%. These are reasons companies give, not measured replacement.

    Why the entry level: cheap implementation

    When code is cheap, value moves to specification, verification and domain knowledge. The BLS projects computer programmers −7% and software developers +10% over 2025–35. On the Remote Labor Index, the best agent finished 2.5% of real freelance projects at launch (October 2025) and about 41% now. Productivity evidence is in MLA 24.

    AI engineer jobs and pay

    AI engineer topped LinkedIn's 2026 fastest-growing list. Levels.fyi has a US median of about $250k for ML/AI software engineers vs $200k for all software engineers. Forward-deployed engineer postings rose more than tenfold in 2026 (Lightcast, via Fortune). Evals are covered in MLA 28, inference in MLA 14.

    What to learn now

    Fundamentals → verification → a domain → agent fluency. Andrew Ng's AI Engineering Skills Map, drawn from 10,000+ postings, names four skills: building AI applications, software fundamentals, using coding agents, and shaping the build.

    How to show you can work with agents
    1. Ship a real project in a public repo.
    2. Include the spec, instruction files (MLA 23), tests and eval suite.
    3. Keep a commit history that shows you reviewing agent output.
    4. Write up the bugs your checks caught.
    5. Time real tasks with and without an agent.

    The full course on this topic is Gnothi's Learn AI, next to Claude Code and the Agentic AI Course, at ocdevel.com/courses.

    More in the resources.

    32 min
  • MLA 004 AI Job Displacement

    AI is already displacing workers in targeted ways - entry-level knowledge workers are being quietly erased from hiring pipelines, freelancers are getting crushed, and the career ladder is being sawed off at the bottom rungs. Yet ML engineer demand has surged 89% with a 3.2:1 talent deficit and $187K median salary. Covers the real displacement data, lessons from the artist bloodbath, the trades escape hatch, the orchestrator treadmill, expert disagreements on timelines, and concrete short- and long-term career moves for ML engineers.

    Links
    • Notes and resources at ocdevel.com/mlg/mla-4
    • Try a walking desk - stay healthy & sharp while you learn & code
    • Generate a podcast - use my voice to listen to any AI generated content you want
    Market Metrics and Displacement Dynamics
    • ML Market: H1 2025 demand rose 89% with a 3.2 to 1 talent deficit. Median salary is $187,500, while Generative AI specialists earn a 40 to 60 percent premium.
    • The "Quiet" Decline: Macro data shows only 4.5% of total layoffs are AI-attributed, but entry-level hiring is collapsing. Stanford/ADP data shows a 13 to 16 percent employment drop for workers aged 22 to 25 in AI-exposed roles since late 2022. UK graduate job postings fell 67%.
    • Corporate Attrition: Salesforce cut 4,000 roles after AI absorbed 30 to 50 percent of workloads. Microsoft cut 15,000 roles as AI began generating 30% of its code. Amazon cut 30,000 jobs while spending $100 billion on AI infrastructure.
    Sector Analysis: Creative and Trades
    • Illustrators: Jobs in China's gaming sector fell 70% in one year. Clients accept "good enough" work (80% quality) at 5% of the cost. Western freelance graphic design and writing jobs fell 18.5% and 30% respectively within eight months of ChatGPT's launch.
    • Manual Labor: The U.S. construction industry lacks 1.7 million workers annually, but apprenticeships take five years. Humanoid robotics are advancing, with Unitree's R1 priced at $5,900 and Figure AI robots completing 1,250 runtime hours at BMW. Full automation is 10 to 15 years away, but partial displacement via smaller crews is closer.
    The Orchestration Treadmill
    • Obsolescence Speed: Prompt engineering roles went from $375,000 salaries to obsolescence in 24 months. AI coding agents like Claude Code now resolve 72% of medium-complexity GitHub issues autonomously.
    • Fragile Expertise: Replacing junior workers with AI prevents the development of future senior talent. New engineers risk "fragile expertise," directed by tools they cannot debug during novel failure modes.
    Economic and Expert Outlook
    • Macro Risks: Daron Acemoglu warns of "so-so automation" that cuts costs without raising productivity, predicting only 0.66% growth over ten years. "Ghost GDP" describes AI-inflated accounts that fail to circulate because machines do not consume.
    • Expert Camps: Accelerationists (Anthropic, OpenAI) predict human-level AI by 2027. Skeptics (LeCun, Marcus) argue LLMs are a dead end lacking world models. Pragmatists (Andrew Ng) suggest shifting from implementation to specification as the cost of code nears zero.
    Tactical Adaptation for ML Engineers
    • Immediate Skills: Master production ML systems, MLOps, LLM evaluation, and safety engineering. Ability to manage deployment risks and hallucination detection is the primary hiring differentiator.
    • Long-term Moats: Focus on "Small AI" (on-device, private), mechanistic interpretability, and deep domain knowledge in healthcare, logistics, or climate science.
    • The Playbook: Optimize for the current three to five year window. Move from being a model builder to a product-focused engineer who understands business tradeoffs and regulatory compliance.
    36 min
  • MLA 029 Is OpenClaw Safe? Uses and Alternatives

    OpenClaw in 2026 is safe for read-only jobs on its own machine and accounts, not as a full-access assistant logged in as you. What it's for, how to harden it and vet skills, what it costs, and the alternatives: Hermes Agent, Gemini Spark and OpenAI's dots.

    Links
    • Notes and resources at ocdevel.com/mlg/mla-29
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    What is OpenClaw?

    An open-source, self-hosted personal agent: an always-on agent loop (MLA 28) that you message from a chat app, with access to your files, shell, browser and accounts. Peter Steinberger started it in November 2025. After he joined OpenAI in February 2026, it moved to the OpenClaw Foundation, a US 501(c)(3) that keeps it MIT licensed. The software is free; you pay for the model and the server.

    Is OpenClaw safe?

    Safe enough for read-only jobs on a machine and accounts that belong to the agent; not safe with full access to your own computer and accounts. The 2026 record:

    • Tens of thousands of instances exposed to the internet (Censys counted 63,070 live at the end of March).
    • A one-click remote code execution bug that stole the gateway token (January) and a pairing-token-to-admin escalation (March); about 720 advisories by November, 14 critical.
    • Malicious ClawHub skills: 341 found by Koi Security in February (ClawHavoc), then 575+ reported by Acronis, both delivering stealers through fake "prerequisites".
    • 2.0's shared sessions are not a security boundary, secrets aren't encrypted at rest, and sandboxing is off by default.

    Injection can't be patched: the prompt-injection docs report adaptive attackers beating defenses over 80% of the time.

    OpenClaw security best practices
    1. Where it runs: a dedicated VPS or spare box, gateway on loopback, reached over Tailscale or SSH, auth token always set. In Docker the container binds to the network, and the tool sandbox is opt-in.
    2. Identity: its own OS user, mailbox, calendar, browser profile and capped API keys.
    3. Permissions: read-only first; approval on anything irreversible; a tool-less reader agent for email; a strong model for any agent that reads untrusted content.
    4. Upkeep: openclaw security audit after every change, a pinned version, weekly log reads.

    One gateway is one trust boundary; give people who don't fully trust each other separate gateways.

    How to vet an OpenClaw skill

    Check the ClawHub audit status and risk level → read the whole SKILL.md (reject any step that runs a terminal command or downloads an archive) → read the scripts for unknown network calls and access to env vars, keychain or SSH keys → check the publisher → install into one workspace.

    How much does OpenClaw cost to run?

    The server needs 1 vCPU and 1 to 2 GB of RAM. The model is the bill:

    20,000 tokens/turn × 48 heartbeats/day ≈ 1M input tokens/day 1M × $2 per M (Sonnet 5.5 input) ≈ $2/day uncached cache reads at 5% of that price → ≈ $0.10/day

    Use a small model for tool-less checks and the strongest model for the agent that acts. The docs advise against local models here (MLA 14 covers self-hosting).

    OpenClaw vs Hermes Agent

    Hermes Agent (Nous Research, MIT, Python) writes and improves its own skills, ships with command approval on, and imports an OpenClaw setup. Pick OpenClaw for channels and integrations, Hermes for stricter defaults.

    OpenClaw alternatives

    Hosted agents trade control for vendor-run isolation: Gemini Spark (AI Pro and Ultra), OpenAI's dots (Pro and Business Premium), Meta's Muse (free tier, US) and Claude Cowork's cloud scheduled tasks. Tiny self-hosted agents (PicoClaw, ZeroClaw, nanobot) save memory, not tokens.

    The full course on this topic is Gnothi's Agentic AI Course, next to Claude Code, at ocdevel.com/courses.

    More in the resources. Next: MLA 30, on AI and programming jobs.

    33 min
  • MLA 028 How to Build an AI Agent in 2026

    An AI agent is a model running tools in a loop toward a goal, and you build one in order: one call, then tools, the loop and evals. Also: frameworks, MCP vs A2A, memory, multi-agent patterns, prompt injection and cost.

    Links
    • Notes and resources at ocdevel.com/mlg/mla-28
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    What is an AI agent?

    A model running tools in a loop toward a goal: model + tools + loop + stop condition (done, turn cap, budget cap, or a human). In a workflow your code decides the next step; in an agent the model does. Coding agents specifically: MLA 22 to MLA 24.

    AI agent vs workflow

    If you can write the steps down, build a workflow. The patterns from Anthropic's Building Effective Agents: prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer. Errors compound: at 95% per step, a 20-step task succeeds about 36% of the time.

    0.95 ^ 20 ≈ 0.36 How to build an AI agent
    1. One model call against ~20 realistic inputs. If it works, stop.
    2. Add tools: name, description, argument schema. Your code runs each call and can refuse.
    3. Add the loop, with turn and spend caps.
    4. Add a verifier the agent must pass, and an eval suite.

    Tool rules: few task-sized tools, namespaced names, readable values over IDs, capped output, descriptions written like a new hire's brief. API first, then page structure, screenshots last.

    AI agent frameworks

    Simple or learning: write the loop. Operates a computer or codebase: Claude Agent SDK. Light handoffs between agents: OpenAI Agents SDK. Durable runs with human approval: LangGraph. Google or Microsoft stack: ADK or Microsoft Agent Framework. No code: n8n's AI Agent node, Zapier Agents. OpenAI's Agent Builder shuts down November 30, 2026.

    MCP vs A2A

    MCP connects an agent to tools; A2A connects agents across organizations. Both sit in the Linux Foundation's Agentic AI Foundation. The 2026-07-28 MCP revision is stateless (no handshake or session), moves long jobs into a tasks extension, and deprecates roots, sampling and logging. MCP's context cost: MLA 23.

    AI agent memory types

    Working (the context window), episodic (past runs), semantic (facts), procedural (instructions, skills). Manage working memory with compaction, context editing and notes; start the rest as files.

    Multi-agent architecture patterns

    Parallelize independent, read-mostly work; keep one writer. Anthropic's research system beat a single agent by 90% at about 15× chat tokens. Cognition's 2026 update: extra agents contribute intelligence, not actions.

    How to evaluate an AI agent

    From Demystifying Evals for AI Agents: start with 20–50 tasks from real failures; code graders first, calibrated LLM judges second; grade outcomes, plus trajectory checks for forbidden steps; isolate trials; read transcripts. Tracing tools: MLA 14.

    pass@k = P(at least 1 of k succeeds) pass^k = P(all k succeed) 0.75^3 ≈ 0.42 Prompt injection and the lethal trifecta

    No session should hold all three of the lethal trifecta: private data, untrusted content, external communication or state changes. When a task needs all three, a human approves side effects. Design patterns: plan-then-execute, dual LLM and four more in this paper.

    Cutting agent cost

    Route easy steps to a small model → cache a stable prompt prefix → cap context and tool output → stop early. Hosting and batch pricing: MLA 14.

    The full course on this topic is Gnothi's Agentic AI Course, next to Claude Code, at ocdevel.com/courses.

    More in the resources. Next: MLA 29, on OpenClaw and personal agents.

    34 min
  • MLA 027 AI Voice, Music and Media Pipelines

    The AI media pipeline: ElevenLabs v4 or Gemini for voice, licensed music over Suno, ComfyUI once a job repeats, and fal or Replicate queues for APIs. Also voice-cloning law, upscaling, captions, loudness targets, and EU and YouTube labeling rules.

    Links
    • Notes and resources at ocdevel.com/mlg/mla-27
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    The AI media pipeline

    script → narration → images and clips (MLA 25, MLA 26) → music and sound effects → edit → upscale → captions → loudness → export → label and upload

    Best AI voice generator

    ElevenLabs Eleven v4 tops the Artificial Analysis speech arena; Gemini 3.8 Flash TTS ranks sixth at about a fifth of the price per character. It scores stock voices on short clips: shortlist there, then test your own long script.

    • Delivery quality: Eleven v4. Cost: Gemini 3.8 Flash TTS.
    • Open weights, license first: Fish Audio Drama 3 (community license), Breeze TTS 2 and Voxtral TTS (non-commercial weights), Kokoro and Qwen3-TTS (Apache 2.0). Chatterbox has been unmaintained since August 2026.
    AI voice cloning: how, and when it's legal

    Record 20 to 30 seconds of clean solo speech. Clone only your own voice or one whose owner signed consent naming the use. Laws: Tennessee's ELVIS Act (it also reaches tools), California and New York replica rules. The federal NO FAKES Act cleared Senate Judiciary in June 2026 and awaits a floor vote.

    Suno vs Udio vs licensed AI music

    Udio has had no downloads since its October 2025 Universal settlement. Suno's download rules: none on Free, 20 a month on Pro, 60 on Premier, with commercial rights while subscribed; Universal and Sony sued over its v6 model in September 2026. Licensed alternatives: Eleven Music, Google's Lyria 3.5 (SynthID-watermarked), and open-weight Stable Audio 3 and ACE-Step 1.5.

    What is ComfyUI?

    A node graph that runs open image, video and audio models and, through Partner Nodes, hosted ones. Learn it when a multi-step job repeats. Automatic1111 and Forge have stalled. One API-format workflow runs on a local server, Comfy Cloud or a Comfy API deployment:

    Export as API JSON → patch prompt and seed → POST to the prompt endpoint → follow progress on the websocket → fetch from history

    fal vs Replicate vs going direct

    Start with an aggregator; go direct for a feature or price it lacks. fal bills per output and doesn't charge for queue wait or its own errors. Replicate bills public models by run time, private ones for all time online. Store the request ID with each job and budget per accepted result:

    real cost per usable second = list price per second ÷ keeper rate Finishing: upscale, captions, loudness

    Topaz Astra 2 (cloud) and Starlight Precise 2.5 (local), or open SeedVR2. WhisperX for word-level caption timing. Spotify normalizes to −14 LUFS, Apple Podcasts asks for −16 ±1, both with true peak at or below −1 dB. YouTube: MP4, H.264, AAC at 48 kHz, source frame rate, about 8 Mbps at 1080p.

    Who owns AI media, and do you have to label it?

    US: no copyright without a human author (Thaler cert denied March 2026), so keep records of your human decisions. EU AI Act Article 50 requires machine-readable marking from August 2, 2026 (code of practice). YouTube requires disclosure of realistic synthetic content, exempts cloning your own voice for voiceovers, and auto-labels files carrying C2PA metadata.

    The full course on this topic is Gnothi's AI Video Generation, next to AI for Marketers, at ocdevel.com/courses.

    More in the resources. Next: MLA 28, on how AI agents are built.

    33 min
  • MLA 026 Best AI Video Generators in 2026

    AI video generation in 2026 has no single winner: Gemini Omni, Wan 3, Seedance 2.5 and MiniMax H3 models are near-tied, Kling 4 leads on control, and Sora is gone. It also covers Runway as a multi-model host, image-to-video, consistency, editing, avatars, cost per minute and free options.

    Links
    • Notes and resources at ocdevel.com/mlg/mla-26
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    What happened to Sora

    OpenAI closed the Sora app on April 26, 2026 and the API on September 24, 2026. Its deprecation page lists "no one-to-one replacement." The closest match is Gemini Omni Flash.

    Best AI video generator

    No single model wins. The top ten of the Artificial Analysis text-to-video arena sit within about 40 Elo points, close to a 55/45 split, and Arena orders them differently. Pick by job:

    • Start from text, or edit afterward: Gemini Omni Flash (3–15 s clips, 3–10 s on Flow's free tier, up to six reference images) or Wan 3.0 (closed weights, 30 s takes, accepts documents).
    • Start from a still: Seedance 2.5, first on image-to-video. Seedance 2.0 is in CapCut.
    • Long directed takes: Kling 4.0: 30 s, 10 keyframes, 15 references.
    • Cheap volume: HeyGen Video 1, built on MiniMax H3.
    • A presenter talking for minutes: an avatar tool such as HeyGen Avatar V.

    Then test the shortlist on three of your own shots and compare cost per kept take.

    Runway vs Veo vs Kling

    Veo 3.1's preview API closed October 22, 2026, and Flow retires Veo 3.1 Fast and Quality on December 5. Runway's Gen-4.5 is no longer near the top, but the Runway API resells Veo, Kling 3 and 4, Seedance 2 and 2.5, Wan 3, H3 Max and Omni (Omni at Google's price). Use one host to switch models; go direct for the newest features or volume pricing.

    Image to video vs text to video

    Start from an image when the look must be exact, because the first frame is the strongest condition. Prompt only the motion and camera. Making the still: MLA 25.

    How to prompt an AI video shot

    subject → one action that finishes → framing → camera (start static) → light

    Duration and aspect ratio go in settings. Describe what you want to see; Omni takes no negative prompt.

    Keeping a character consistent across shots
    1. Reuse one reference pack per character in every shot.
    2. Keep wardrobe and prop wording identical, from a one-page production bible.
    3. Use each shot's last frame as the next shot's first frame.
    4. Generate fresh instead of extending far: Omni's extension sees only the last 10 seconds.
    Can AI edit video?

    Within a shot: relight, restyle, swap objects, change the angle. Wan 3.0 and Omni Flash lead the editing board. Cutting shots together stays in an editor (MLA 27).

    How much does AI video cost?

    Per generated minute at 1080p (arena prices): HeyGen Video 1 $2.40, MiniMax H3 $4.80, Omni Flash 1.2 $6.26, Wan 3.0 $12, Seedance 2.5 $34.12.

    cost per usable minute = price per generated minute × takes per keeper

    Draft at Omni's 360p, a third of the 720p price.

    Free AI video generators
    • Flow free tier: Omni Flash, 3–10 s clips (the Gemini app needs a paid plan).
    • HeyGen playground: two 5-second clips a day.
    • Wan 2.2 5B: Apache 2.0, runs on a 24 GB GPU, no audio.
    • LTX-2.5: native audio, free for companies under $10M revenue.
    • MiniMax H3: the strongest open model, but its license excludes the US, EU, UK and South Korea unless MiniMax grants permission.
    • Renting a GPU instead: MLA 14.

    The full course on this topic is Gnothi's AI Video Generation, next to AI for Marketers, at ocdevel.com/courses.

    More in the resources. Next: MLA 27, on the AI media pipeline.

    31 min
  • MLA 025 Best AI Image Generators in 2026

    The best AI image generator in 2026 by blind votes is GPT Image 2.6, but Nano Banana 2.1 costs a sixth as much and Flux 3 Klein runs on your own GPU. It also covers editing and prompting, text in images, consistent characters, open-weight licenses and commercial use by tool.

    Links
    • Notes and resources at ocdevel.com/mlg/mla-25
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    Best AI image generator in 2026

    OpenAI's GPT Image 2.6 (ChatGPT Images 2.6, November 4, 2026) leads on blind human votes: the top five slots on the Artificial Analysis text-to-image board, and first place in every category on Arena, including text rendering, portraits and photorealism. An Elo gap converts to a win rate: 100 points ≈ 64% of votes, 200 ≈ 76%. Midjourney has no API, so neither board ranks it.

    Shortlist three from the boards, run ten of your own prompts through each, then compare cost per usable image (price ÷ acceptance rate).

    GPT Image vs Nano Banana vs Midjourney vs Flux
    • GPT Image 2.6 (Sunburst precise, Flare fast): best quality, text and editing. About $0.21 per square image at max quality; SVG and GIF output; org verification required for the API.
    • Nano Banana 2.1 (Google): about 85 Elo behind at a sixth of the price, $0.034 per 1K image, half in batch. 14 references (10 objects, 4 characters), Search grounding, SynthID on every image, no free API tier (docs).
    • Midjourney V8.2: the art-directed look. Companies over $1M revenue need Pro or Mega to own outputs; no automation; you indemnify Midjourney.
    • Flux 3 Image Klein: the practical open-weight model (below).
    • Seedream 5.5 (ByteDance): top dozen at about $0.02 an image.
    How to edit AI images

    Describe the scene in sentences, say what to keep, change one thing per instruction. Control, loosest to tightest: instruction → markup → mask → bounding box with pixel restoration. OpenAI's masks are guidance, not a hard boundary. For multi-turn work, explore in chat, then redo the final edit as one instruction on the original.

    Best AI for text in images

    GPT Image first, Nano Banana 2.1 next. Recraft V4 Vector outputs editable SVG; Seedream 5.5 and Qwen-Image-2.1 output transparent PNGs. Set final brand type yourself.

    Consistent characters: references, then LoRA
    1. Build a reference sheet (front, three-quarter, profile) and pass it with every request.
    2. If fine details drift, train a LoRA on open weights: 15–40 images for a style, under an hour on an RTX 4090 (Hugging Face guide).
    3. Train on the base model, run on the distilled one, pick checkpoints by eye.
    Self-hosting open-weight image models
    • Flux 3 Image Klein: 5.6B, free commercial use under $5M revenue, 8 GB VRAM (INT8).
    • Qwen-Image-2.1: 7B, research license, non-commercial.
    • MiniMax H3-Image: license excludes the US, EU, UK and South Korea.
    • Apache 2.0: FLUX.2 klein 4B (~13 GB), Z-Image Turbo (16 GB), Qwen-Image 20B.

    Renting GPUs: MLA 14. ComfyUI, hosted APIs, and the copyright and labeling law: MLA 27.

    Can I use AI images commercially?
    • OpenAI: you own outputs.
    • Google: claims no ownership; unpaid API usage can be read by human reviewers.
    • Midjourney: paid plans, revenue rule above.
    • Adobe Firefly: IP indemnity for business and enterprise customers on Adobe's own models; partner models get narrower or no coverage.
    • Open weights: the weights' license decides.

    The full course on this topic is Gnothi's AI Video Generation, next to AI for Marketers, at ocdevel.com/courses.

    More in the resources. Next: MLA 26, on AI video generation.

    30 min
  • MLG 036 Autoencoders

    Auto encoders are neural networks that compress data into a smaller "code," enabling dimensionality reduction, data cleaning, and lossy compression by reconstructing original inputs from this code. Advanced auto encoder types, such as denoising, sparse, and variational auto encoders, extend these concepts for applications in generative modeling, interpretability, and synthetic data generation.

    Links
    • Notes and resources at ocdevel.com/mlg/36
    • Try a walking desk - stay healthy & sharp while you learn & code
    • Build the future of multi-agent software with AGNTCY.
    • Thanks to T.J. Wilder from intrep.io for recording this episode!
    Fundamentals of Autoencoders
    • Autoencoders are neural networks designed to reconstruct their input data by passing data through a compressed intermediate representation called a "code."
    • The architecture typically follows an hourglass shape: a wide input and output separated by a narrower bottleneck layer that enforces information compression.
    • The encoder compresses input data into the code, while the decoder reconstructs the original input from this code.
    Comparison with Supervised Learning
    • Unlike traditional supervised learning, where the output differs from the input (e.g., image classification), autoencoders use the same vector for both input and output.
    Use Cases: Dimensionality Reduction and Representation
    • Autoencoders perform dimensionality reduction by learning compressed forms of high-dimensional data, making it easier to visualize and process data with many features.
    • The compressed code can be used for clustering, visualization in 2D or 3D graphs, and input into subsequent machine learning models, saving computational resources and improving scalability.
    Feature Learning and Embeddings
    • Autoencoders enable feature learning by extracting abstract representations from the input data, similar in concept to learned embeddings in large language models (LLMs).
    • While effective for many data types, autoencoder-based encodings are less suited for variable-length text compared to LLM embeddings.
    Data Search, Clustering, and Compression
    • By reducing dimensionality, autoencoders facilitate vector searches, efficient clustering, and similarity retrieval.
    • The compressed codes enable lossy compression analogous to audio codecs like MP3, with the difference that autoencoders lack domain-specific optimizations for preserving perceptually important data.
    Reconstruction Fidelity and Loss Types
    • Loss functions in autoencoders are defined to compare reconstructed outputs to original inputs, often using different loss types depending on input variable types (e.g., Boolean vs. continuous).
    • Compression via autoencoders is typically lossy, meaning some information from the input is lost during reconstruction, and the areas of information lost may not be easily controlled.
    Outlier Detection and Noise Reduction
    • Since reconstruction errors tend to move data toward the mean, autoencoders can be used to reduce noise and identify data outliers.
    • Large reconstruction errors can signal atypical or outlier samples in the dataset.
    Denoising Autoencoders
    • Denoising autoencoders are trained to reconstruct clean data from noisy inputs, making them valuable for applications in image and audio de-noising as well as signal smoothing.
    • Iterative denoising as a principle forms the basis for diffusion models, where repeated application of a denoising autoencoder can gradually turn random noise into structured output.
    Data Imputation
    • Autoencoders can aid in data imputation by filling in missing values: training on complete records and reconstructing missing entries for incomplete records using learned code representations.
    • This approach leverages the model's propensity to output 'plausible' values learned from overall data structure.
    Cryptographic Analogy
    • The separation of encoding and decoding can draw parallels to encryption and decryption, though autoencoders are not intended or suitable for secure communication due to their inherent lossiness.
    Advanced Architectures: Sparse and Overcomplete Autoencoders
    • Sparse autoencoders use constraints to encourage code representations with only a few active values, increasing interpretability and explainability.
    • Overcomplete autoencoders have a code size larger than the input, often in applications that require extraction of distinct, interpretable features from complex model states.
    Interpretability and Research Example
    • Research such as Anthropic's "Towards Monosemanticity" applies sparse autoencoders to the internal activations of language models to identify interpretable features correlated with concrete linguistic or semantic concepts.
    • These models can be used to monitor and potentially control model behaviors (e.g., detecting specific language usage or enforcing safety constraints) by manipulating feature activations.
    Variational Autoencoders (VAEs)
    • VAEs extend autoencoder architecture by encoding inputs as distributions (means and standard deviations) instead of point values, enforcing a continuous, normalized code space.
    • Decoding from sampled points within this space enables synthetic data generation, as any point near the center of the code space corresponds to plausible data according to the model.
    VAEs for Synthetic Data and Rare Event Amplification
    • VAEs are powerful in domains with sparse data or rare events (e.g., healthcare), allowing generation of synthetic samples representing underrepresented cases.
    • They can increase model performance by augmenting datasets without requiring changes to existing model pipelines.
    Conditional Generative Techniques
    • Conditional autoencoders extend VAEs by allowing controlled generation based on specified conditions (e.g., generating a house with a pool), through additional decoder inputs and conditional loss terms.
    Practical Considerations and Limitations
    • Training autoencoders and their variants requires computational resources, and their stochastic training can produce differing code representations across runs.
    • Lossy reconstruction, lack of domain-specific optimizations, and limited code interpretability restrict some use cases, particularly where exact data preservation or meaningful decompositions are required.
    1 hr 6 min
  • MLG 035 Large Language Models 2

    At inference, large language models use in-context learning with zero-, one-, or few-shot examples to perform new tasks without weight updates, and can be grounded with Retrieval Augmented Generation (RAG) by embedding documents into vector databases for real-time factual lookup using cosine similarity. LLM agents autonomously plan, act, and use external tools via orchestrated loops with persistent memory, while recent benchmarks like GPQA (STEM reasoning), SWE Bench (agentic coding), and MMMU (multimodal college-level tasks) test performance alongside prompt engineering techniques such as chain-of-thought reasoning, structured few-shot prompts, positive instruction framing, and iterative self-correction.

    Links
    • Notes and resources at ocdevel.com/mlg/mlg35
    • Build the future of multi-agent software with AGNTCY
    • Try a walking desk stay healthy & sharp while you learn & code
    In-Context Learning (ICL)
    • Definition: LLMs can perform tasks by learning from examples provided directly in the prompt without updating their parameters.
      • Types:
        • Zero-shot: Direct query, no examples provided.
        • One-shot: Single example provided.
        • Few-shot: Multiple examples, balancing quantity with context window limitations.
      • Mechanism: ICL works through analogy and Bayesian inference, using examples as semantic priors to activate relevant internal representations.
      • Emergent Properties: ICL is an "inference-time training" approach, leveraging the model's pre-trained knowledge without gradient updates; its effectiveness can be enhanced with diverse, non-redundant examples.
    Retrieval Augmented Generation (RAG) and Grounding
    • Grounding: Connecting LLMs with external knowledge bases to supplement or update static training data.
      • Motivation: LLMs' training data becomes outdated or lacks proprietary/specialized knowledge.
      • Benefit: Reduces hallucinations and improves factual accuracy by incorporating current or domain-specific information.
    • RAG Workflow:
      1. Embedding: Documents are converted into vector embeddings (using sentence transformers or representation models).
      2. Storage: Vectors are stored in a vector database (e.g., FAISS, ChromaDB, Qdrant).
      3. Retrieval: When a query is made, relevant chunks are extracted based on similarity, possibly with re-ranking or additional query processing.
      4. Augmentation: Retrieved chunks are added to the prompt to provide up-to-date context for generation.
      5. Generation: The LLM generates responses informed by the augmented context.
      • Advanced RAG: Includes agentic approaches—self-correction, aggregation, or multi-agent contribution to source ingestion, and can integrate external document sources (e.g., web search for real-time info, or custom datasets for private knowledge).
    LLM Agents
    • Overview: Agents extend LLMs by providing goal-oriented, iterative problem-solving through interaction, memory, planning, and tool usage.
    • Key Components:
      • Reasoning Engine (LLM Core): Interprets goals, states, and makes decisions.
      • Planning Module: Breaks down complex tasks using strategies such as Chain of Thought or ReAct; can incorporate reflection and adjustment.
      • Memory: Short-term via context window; long-term via persistent storage like RAG-integrated databases or special memory systems.
      • Tools and APIs: Agents select and use external functions—file manipulation, browser control, code execution, database queries, or invoking smaller/fine-tuned models.
    • Capabilities: Support self-evaluation, correction, and multi-step planning; allow integration with other agents (multi-agent systems); face limitations in memory continuity, adaptivity, and controllability.
    • Current Trends: Research and development are shifting toward these agentic paradigms as LLM core scaling saturates.
    Multimodal Large Language Models (MLLMs)
    • Definition: Models capable of ingesting and generating across different modalities (text, image, audio, video).
    • Architecture:
      • Modality-Specific Encoders: Convert raw modalities (text, image, audio) into numeric embeddings (e.g., vision transformers for images).
      • Fusion/Alignment Layer: Embeddings from different modalities are projected into a shared space, often via cross-attention or concatenation, allowing the model to jointly reason about their content.
      • Unified Transformer Backbone: Processes fused embeddings to allow cross-modal reasoning and generates outputs in the required format.
    • Recent Advances: Unified architectures (e.g., GPT-4o) use a single model for all modalities rather than switching between separate sub-models.
    • Functionality: Enables actions such as image analysis via text prompts, visual Q&A, and integrated speech recognition/generation.
    Advanced LLM Architectures and Training Directions
    • Predictive Abstract Representation: Incorporating latent concept prediction alongside token prediction (e.g., via autoencoders).
    • Patch-Level Training: Predicting larger "patches" of tokens to reduce sequence lengths and computation.
    • Concept-Centric Modeling: Moving from next-token prediction to predicting sequences of semantic concepts (e.g., Meta's Large Concept Model).
    • Multi-Token Prediction: Training models to predict multiple future tokens for broader context capture.
    Evaluation Benchmarks (as of 2025)
    • Key Benchmarks Used for LLM Evaluation:
      • GPQA (Diamond): Graduate-level STEM reasoning.
      • SWE Bench Verified: Real-world software engineering, verifying agentic code abilities.
      • MMMU: Multimodal, college-level cross-disciplinary reasoning.
      • HumanEval: Python coding correctness.
      • HLE (Human's Last Exam): Extremely challenging, multimodal knowledge assessment.
      • LiveCodeBench: Coding with contamination-free, up-to-date problems.
      • MLPerf Inference v5.0 Long Context: Throughput/latency for processing long contexts.
      • MultiChallenge Conversational AI: Multiturn dialogue, in-context reasoning.
      • TAUBench/PFCL: Tool utilization in agentic tasks.
      • TruthfulnessQA: Measures tendency toward factual accuracy/robustness against misinformation.
    Prompt Engineering: High-Impact Techniques
    • Foundational Approaches:
      • Few-Shot Prompting: Provide pairs of inputs and desired outputs to steer the LLM.
      • Chain of Thought: Instructing the LLM to think step-by-step, either explicitly or through internal self-reprompting, enhances reasoning and output quality.
      • Clarity and Structure: Use clear, detailed, and structured instructions—task definition, context, constraints, output format, use of delimiters or markdown structuring.
      • Affirmative Directives: Phrase instructions positively ("write a concise summary" instead of "don't write a long summary").
      • Iterative Self-Refinement: Prompt the LLM to review and improve its prior response for better completeness, clarity, and factuality.
      • System Prompt/Role Assignment: Assign a persona or role to the LLM for tailored behavior (e.g., "You are an expert Python programmer").
    • Guideline: Regularly consult official prompting guides from model developers as model capabilities evolve.
    Trends and Research Outlook
    • Inference-time compute is increasingly important for pushing the boundaries of LLM task performance.
    • Agentic LLMs and multimodal reasoning represent the primary frontiers for innovation.
    • Prompt engineering and benchmarking remain essential for extracting optimal performance and assessing progress.
    • Models are expected to continue evolving with research into new architectures, memory systems, and integration techniques.
    46 min
  • MLG 034 Large Language Models 1

    Large language models (LLMs) train compute-optimally at about 20 tokens per parameter (Chinchilla), often past that for cheaper inference, then align through supervised fine-tuning and RLHF, where human rankings train a reward model and PPO tunes the LLM against it. Also covers emergent abilities, mixture of experts, reward hacking, chain of thought and reasoning models.

    Links
    • Notes and resources at ocdevel.com/mlg/34
    • Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners
    LLMs are scaled-up transformers

    Large language models (LLMs) are transformers (MLG 033): stacks of self-attention and feed-forward layers that train in parallel, which recurrent neural networks (RNNs) could not. The classical NLP background is in MLG 018 to 020, and RNNs and embeddings in 022 and 023.

    Scaling laws: Kaplan vs Chinchilla
    • Scaling Laws for Neural Language Models (Kaplan et al., 2020): test loss (cross-entropy) falls as a power law in parameters, training tokens and compute, over more than seven orders of magnitude. The network's shape, depth against width, matters far less than scale. Growing parameters with data fixed brings diminishing returns from overfitting; the penalty depends on N^0.74/D (N parameters, D tokens), so data need only grow sublinearly with model size.
    • Training Compute-Optimal Large Language Models (Hoffmann et al., DeepMind, 2022), the Chinchilla paper: for a fixed compute budget, scale parameters and tokens together, about 20 tokens per parameter. Earlier large models were undertrained: the 70B-parameter Chinchilla beat the 280B Gopher and the 175B GPT-3.

    GPT-2 had 1.5 billion parameters and GPT-3 175 billion. OpenAI never published GPT-4's size; outside estimates run near 1.8 trillion, as a mixture of experts.

    Training-optimal vs inference-optimal

    Chinchilla's ratio minimizes training cost. A model serving many users can spend more on inference over its lifetime than on training, so labs train smaller models well past that ratio: Llama 2 on 2 trillion tokens, Llama 3 on 15 trillion. Test-time compute is the other lever: more computation per query for reasoning steps, sampled answers and self-critique, at higher latency and cost per query.

    Emergent abilities

    Emergent Abilities of Large Language Models (Wei et al., 2022) describes abilities absent in small models that appear sharply past a scale threshold:

    • In-context learning (ICL): doing a new task from examples in the prompt (one-shot or few-shot).
    • Instruction following: carrying out instructions for tasks not seen in training.
    • Multi-step reasoning: arithmetic, common-sense and symbolic tasks, helped by chain of thought.

    Are Emergent Abilities of Large Language Models a Mirage? (Schaeffer et al., 2023) argues many are artifacts of all-or-nothing metrics; scored with continuous metrics, the same abilities improve smoothly.

    Mixture of experts (MoE)

    An MoE layer replaces a transformer block's feed-forward layer with many expert feed-forward networks plus a router, usually a linear layer and a softmax. For each token, in each MoE layer, the router picks the top-k experts (Mixtral: 2 of 8) and sums their outputs weighted by its scores; the rest sit idle for that token. This is sparse activation, or conditional computation. What each expert specializes in is learned and opaque, rarely a topic a person would name.

    • Gain: many parameters for little compute per token. DeepSeek-V3 and R1 have 671B parameters with 37B active per token (DeepSeek-V3 Technical Report).
    • Memory: every expert must still sit in GPU or system memory, so running an MoE model locally takes memory for its total size, not its active size.
    • Load balancing: auxiliary losses keep the router from overusing a few experts.
    • Communication: experts spread across GPUs need tokens routed between devices.
    • Overfitting: the added parameters call for more regularization.

    Many frontier models use MoE; dense models remain common (Llama 3, for one).

    Pretraining, supervised fine-tuning and RLHF pretraining -> supervised fine-tuning (SFT) -> RLHF
    1. Pretraining: self-supervised next-token prediction on web-scale text (Common Crawl, C4 and similar), the longest and costliest phase. The result, a foundation model, only continues text. A frontier model is one of the newest and most capable; they change quickly, so check a current leaderboard such as Arena (formerly LMArena) or Artificial Analysis.
    2. Supervised fine-tuning: continued training on curated prompt-response pairs, such as questions with answers, articles with summaries, or instructions with code. General-purpose models fine-tune on many tasks at once. The risks are overfitting, worst for small models, and catastrophic forgetting of pretraining knowledge, both managed with hyperparameters such as learning rate and epochs (MLG 027).
    3. Reinforcement learning from human feedback (RLHF), as in InstructGPT (Ouyang et al., 2022):
    SFT model writes several responses -> humans rank them -> reward model trained on the rankings (supervised) -> LLM tuned against the reward model with RL, usually PPO

    The reward model is a separate network, often initialized from a copy of the LLM, that predicts a score for a prompt-response pair. Proximal Policy Optimization (PPO, MLG 029) updates the LLM to raise that score, with a penalty that keeps it close to the SFT model. Direct Preference Optimization (DPO) trains on the ranked pairs directly, with no separate reward model.

    Alignment and reward hacking

    RLHF's goal is alignment: outputs that are helpful, honest and harmless, qualities that fixed labeled data captures poorly. It costs consistent, high-quality human rankings and is harder to tune than SFT. Reward hacking, or specification gaming, is the model exploiting the reward model instead of improving, a practical case of the paperclip-maximizer thought experiment. RLHF-tuned models learned that length and a confident tone win ratings, so labs control for verbosity.

    Chain of thought and reasoning models
    • Chain-of-thought (CoT) prompting: the model writes intermediate steps before its answer. Few-shot CoT gives worked examples (Wei et al., 2022); zero-shot CoT appends "Let's think step by step" (Kojima et al., 2022). It improves arithmetic, common-sense, symbolic and coding tasks, and leaves a readable trace for debugging and safety monitoring.
    • Self-consistency: sample several chains and take the majority answer, an ensemble over reasoning paths.
    • Tree of thoughts: generate and score several candidate next steps, search the branches breadth-first or depth-first, and backtrack from dead ends.
    • Reasoning models (OpenAI o1 and later, DeepSeek R1) are trained with reinforcement learning to produce a long chain of thought before answering; the network architecture is unchanged.

    A chain of thought costs extra tokens and latency, so it pays on multi-step problems more than simple lookups. Prompt wording still changes output quality; Anthropic's Prompt Engineering Interactive Tutorial covers chain of thought among other techniques.

    Where to learn about LLMs
    1. The transformer resources in MLG 033.
    2. The Chinchilla and InstructGPT papers linked above.
    3. Nathan Lambert's RLHF book, free online: reward models, PPO and DPO.

    Next: MLG 035, on in-context learning, retrieval-augmented generation (RAG), agents and benchmarks.

    46 min