Agentic AI
Agentic AI systems plan, use tools, and take multi-step actions toward a goal — moving beyond single prompts to autonomous task execution.
1019 concepts from Python basics to Agentic AI, organized by dependency so you always know what to learn next. Includes Telugu translations.
Python + Math + Data
Agentic AI systems plan, use tools, and take multi-step actions toward a goal — moving beyond single prompts to autonomous task execution.
Agile is an iterative development methodology: short sprints, frequent releases, constant adjustment — the opposite of writing a full spec upfront.
Agile is an iterative development approach; Scrum organizes work into 2-week sprints with daily standups, sprint planning, and retrospectives.
The recurring meetings of a sprint: planning, daily stand-up, review, retrospective.
AI is the broadest field (making machines smart), ML is a subset (learning from data), Deep Learning is a subset of ML (using neural networks), and Generative AI creates new content.
AI powers search, recommendations, fraud detection, medical imaging, self-driving, translation, and content generation across nearly every industry today.
AI's arc spans 1956 Dartmouth, two AI winters, the deep learning revolution (2012), and the transformer era (2017-now) reshaping every industry.
An API (Application Programming Interface) defines how software components communicate; REST APIs use HTTP requests to exchange JSON data between frontend and backend.
The agreed doorway one piece of software uses to ask another for data or an action.
The periodic review where your work, goals and pay are discussed.
How roles, skills and seniority progress over years in software.
Continuous Integration builds and tests code on every commit; Continuous Deployment automatically releases validated changes to production.
Renting computing from a provider (IaaS, PaaS, SaaS) instead of owning servers.
A teammate reads and comments on a change before it merges.
Fixed price, time and materials, and retainer: who carries the risk.
Systems that store data durably and answer queries about it.
The five categories of tools every team uses: tracking, code, build, docs, chat.
Predicting effort or time, and how wrong such predictions usually are.
The frontend is what users see and interact with (UI/UX), while the backend handles data processing, business logic, and server-side operations.
Generative AI produces new content — text, images, code, audio, video — by learning the distribution of training data and sampling from it.
When production breaks: restore first, understand second, write it down.
The smallest product that answers a real question about customers.
POC, prototype, MVP, GA, sunset, and the question each stage answers.
Scope, time and cost, and keeping all three honest.
What the software must do (functional) and how well (non-functional).
BRD, FRD, HLD, LLD, ADR, RTM, RCA and when each is written.
The high-level picture of the parts of a system and how they talk.
The SDLC is the end-to-end process of building software: plan, design, build, test, deploy, maintain — the loop every team runs through.
Tech companies range from FAANG-scale platforms to bootstrapped startups, each with distinct cultures, business models, and engineering practices.
Tech teams include engineers, PMs, designers, data scientists, ML engineers, DevOps, and SREs — each owning distinct slices of the product lifecycle.
Software is built and sold by companies of many kinds, from services firms to product companies and startups.
Version control tracks changes to code over time, enabling collaboration, history, branching, and rollback; Git is the industry standard.
Artificial intelligence is the field of building systems that perform tasks normally requiring human intelligence — perception, reasoning, language, decision-making.
Machine learning is the subset of AI where systems learn patterns from data instead of being explicitly programmed with rules.
Writing and speaking so that others can act on what you say.
The unwritten habits that make you easy to work with.
`.gitignore` keeps listed files untracked; it does not untrack a file already committed, and a committed secret stays in history, so rotate it.
A* orders the heap by cost so far plus an admissible guess of the cost to go, so it expands fewer cells than Dijkstra and still returns a shortest path. A guess that overestimates can return a longer route.
`abc.ABC` plus `@abstractmethod` defines a class that can't be instantiated until subclasses implement the required methods, enforcing interface contracts.
A test file that states what finished means: you build one checkpoint at a time until it passes.
deque powers sliding-window maximums, BFS queues, and bounded-history buffers via `maxlen`, all leveraging O(1) operations at both ends.
Aho-Corasick adds failure links to a trie, the KMP fall-back generalized to many words, so one pass over the text finds every occurrence of every word in O(n + k) after a build proportional to the total word length.
Big-O analysis, searching, sorting, and the tradeoffs that decide which algorithm fits your data — the foundation of efficient code.
Amortized cost is the total cost of any sequence of n operations divided by n. The aggregate method sums the total, the accounting method charges coins and keeps the bank at zero or above, and the potential method adds the change in a potential function to the actual cost.
An r-approximation never costs more than r times the best answer. Vertex cover has a 2-approximation in O(m) (take both endpoints of uncovered edges), greedy set cover has ratio about ln n, and metric TSP has a 2-approximation through the MST.
`asyncio` is Python's event-loop library for `async`/`await` code — `gather` runs coroutines concurrently and `run` boots the loop from sync land.
The fewest nodes N(h) of an AVL tree of height h follows N(h) = 1 + N(h - 1) + N(h - 2), a Fibonacci recurrence, so the height is at most about 1.44 log2 n.
An aware datetime carries an offset and a naive one is a guess; record UTC, store ISO strings and convert only for display.
A tree whose nodes are as wide as a disk page, holding t - 1 to 2t - 1 sorted keys with all leaves at one depth. It grows at the root by splitting full nodes, so a lookup reads about log base t of n pages.
A B+ tree keeps sorted keys in linked leaf blocks under internal blocks of separators. A full block splits in half and copies a separator up, so every non-root block stays at least half full and all leaves stay at one depth. Lookup is O(log_B n) reads and a range scan is O(log_B n + k / B).
Build an answer one choice at a time with choose, explore, un-choose: add an option to the shared state, recurse, then remove it so the next branch starts clean. The call stack is the decision tree.
Bellman-Ford relaxes every edge for V - 1 rounds in O(V times E) time. It allows negative edges, and one more round that still improves a distance means a reachable negative cycle.
Best, worst, average and expected case pick which cost function you bound, and O, Omega and Theta then describe it. Insertion sort is Theta(n) in its best case and Theta(n squared) in its worst case.
Big O describes how an algorithm's time/space grows with input size. O(1) is constant, O(log n) is logarithmic, O(n) is linear, O(n log n) is linearithmic, O(n²) is quadratic.
Binary search finds a target in a sorted array by halving the search space each step, achieving O(log n) time. For 1 million items, it needs only ~20 comparisons.
When a yes or no test flips from False to True once (is monotone), you can binary search the range of possible answers for the smallest one that passes, with cost equal to the probes times the cost of one test.
A BST keeps left subtree < node < right subtree, giving O(log n) search/insert/delete when balanced — degrading to O(n) on sorted input.
A binary tree is a hierarchical structure where each node has at most two children — the foundation for BSTs, heaps, and expression parsing.
A binary tree has at most two children per node, traversed with DFS (inorder, preorder, postorder) or BFS (level by level). Graphs use adjacency lists and can have cycles.
A graph is bipartite exactly when it has no odd cycle. BFS two-coloring tests it in O(V + E), and the first same-color edge is a witness.
A maximum matching grows by flipping augmenting paths, each of which adds exactly one pair. Kuhn's algorithm costs O(V times E); Hopcroft-Karp costs O(E times the square root of V).
bisect_left and bisect_right find a place in a sorted list in O(log n) comparisons, and their difference counts equal items. insort then shifts later pointers, so each insertion is O(n) overall.
Store a set of up to about 20 items as the bits of one integer and use it as part of the DP state. A small travelling salesman then costs O(2^n * n^2) instead of (n - 1)! routes.
A number from 0 to 2^n - 1 is a subset of n items (bit i set means item i is in), so one loop lists all subsets in O(n * 2^n). The same mask can sit inside a DP state, as in travelling salesman at O(2^n * n^2).
& | ^ ~ << >> work on every bit column of an integer at once. A mask (such as & 0xFF) keeps chosen bits; in Python ~x equals -x - 1 because negatives behave as if they had endless leading ones.
A disk hands out whole blocks and sequential reads beat random ones, so a disk structure is judged by block reads. With B entries per block, a wide tree finds a key in O(log_B n) reads.
A Bloom filter keeps m bits and k hash functions. Adding an item turns on k bits, and a query says maybe only if all k are on. It gives false positives at rate about (1 - e^(-kn/m))^k, never false negatives, and cannot delete.
A comparison gives a True/False array, and indexing with it selects the matching rows.
A branch is a separate line of commits; `git merge` joins it back, and a conflict is resolved by editing the file, then `git add` and `git commit`.
One DFS with discovery times tin and low-links low finds every bridge (tree edge u to v with low[v] greater than tin[u]) and articulation point in O(V + E) time.
The requests library sends an HTTP request and returns a response. Pass a timeout, call raise_for_status() before .json(), and keep API keys in environment variables, never in the code.
A request is a list of role and content messages plus `max_tokens`; the response holds text, `usage` and a `stop_reason`, and the service keeps no memory.
A closure captures variables from its enclosing scope, letting inner functions remember state after the outer function returns.
Membership is O(n) on a list but O(1) on average on a set or dict, list.pop(0) is O(n) while deque.popleft() is O(1), heappush and heappop are O(log n), and sorted is O(n log n).
Consistent hashing puts servers and keys on a hash ring, and a key belongs to the first server point clockwise. Adding a server moves only about 1/(S+1) of the keys, all to the new server, and virtual nodes even out the load. Lookup is a binary search in O(log(S v)).
Context managers define __enter__ and __exit__ for the with statement, guaranteeing cleanup (closing files, releasing connections) even when exceptions occur.
History is a list you resend and trim yourself, and you record a turn only after the call succeeds.
A count-min sketch is a grid of d rows and w counters with one hash per row. Reading an item takes the minimum of its d cells, so the estimate is never below the true count and exceeds it by at most epsilon times N with probability 1 - delta when w = ceil(e / epsilon) and d = ceil(ln(1 / delta)).
`collections.Counter` is a dict subclass for counting hashable items, supporting `.most_common(n)` and arithmetic like `c1 + c2` or `c1 - c2`.
A counting Bloom filter replaces each bit with a small counter so items can be removed: add increments the k counters and remove decrements them. It costs several times the memory of the bit version, and counter overflow breaks the guarantee.
An inversion is a pair i < j with items[i] > items[j]. Merge sort counts the pairs that cross the two halves while it merges: when a right value is taken, it jumps over every left value still waiting. Total time O(n log n).
Counting sort counts each whole-number value and writes them out in order in O(n + k). Radix sort applies a stable counting sort to one digit at a time, ones digit first, in O(d(n + b)).
`read_csv` guesses types and `to_csv` writes the index unless you pass `index=False`.
In many dimensions the nearest and farthest points are almost the same distance away, so tree indexes such as the k-d tree can skip almost nothing and approach a full scan.
Data loading reads raw data from files (CSV, JSON, databases) into structured formats like Pandas DataFrames for analysis and preprocessing.
A data structure keeps many values together so that some jobs are easy, and an algorithm is the list of steps that does a job and finishes; the cost of a job depends on both.
Data visualization transforms numbers into charts that reveal patterns, outliers, and distributions. Choose chart types based on your data: line for trends, scatter for correlations, bar for comparisons, histogram for distributions.
`@dataclass` auto-generates `__init__`, `__repr__`, and `__eq__` from typed class attributes, removing boilerplate for simple data-holding classes.
A DataFrame is a 2D labeled data structure with named columns and an index. It supports boolean filtering, groupby aggregation, merging, and vectorized operations.
`datetime`, `timedelta` and ISO 8601 strings handle dates and times; subtracting two datetimes gives a `timedelta`.
A decorator is a function that wraps another function with extra behavior using @decorator syntax. Common uses include timing, logging, caching, and access control.
`defaultdict(list)` auto-creates a missing key's value using the supplied factory, eliminating boilerplate `if key not in d` checks when grouping data.
`collections.deque` is a doubly-linked list giving O(1) appends and pops from both ends, unlike list which is O(n) for left-side operations.
Dijkstra's algorithm finds shortest paths in O((V+E) log V) from one source to all nodes in a weighted graph with non-negative edges, using a min-heap.
Divide the input into smaller copies of the same problem, conquer each by recursion, and combine the answers. A base case stops the splitting, and the cost depends on how many pieces there are, how small each is, and how costly the combine step is.
A doubly linked list adds a `prev` pointer to each node, enabling O(1) deletion given a node reference and bidirectional traversal at the cost of extra memory.
Common DP patterns include knapsack, longest common subsequence, edit distance, and coin change — recognize the recurrence and the state shape.
Double-underscore methods like `__repr__`, `__add__` and `__eq__` hook into Python's syntax, letting your objects work with `print()`, `+` and `==`.
Dynamic programming solves problems by combining solutions to overlapping subproblems — either top-down with memoization or bottom-up with tabulation.
`enum.Enum` defines a set of named, immutable constants that compare by identity — safer than bare strings or ints for state machines and config.
try/except catches runtime errors without crashing. Catch specific exceptions (ValueError, FileNotFoundError), use finally for cleanup, and raise custom exceptions for clear error messages.
Prove a greedy rule by swapping its choice into any best answer without making it worse (exchange), or by showing greedy is never behind any other answer at every step (stays ahead).
Amortized is a deterministic guarantee on the total over any sequence of operations. Expected averages over random choices, so one run can be unlucky. A hash insert is expected amortized O(1); randomized quick sort is expected O(n log n).
f-strings interpolate expressions at compile time — faster than `%` or `.format()` — and support format specs like `f'{x:.2f}'` and debug `f'{x=}'`.
x^n is the square of x^(n//2), times one more x if n is odd, so it needs O(log n) multiplications instead of n. Reducing modulo m after every multiplication keeps numbers small, and Python's pow(x, n, m) does exactly this.
FastAPI is a modern async Python web framework — type hints drive automatic validation, OpenAPI docs, and serialization with near-zero boilerplate.
A Fenwick tree (binary indexed tree) keeps in cell i the sum of the lowbit(i) = i & -i values ending at position i. A prefix query removes the lowest set bit, an update adds it, and both take O(log n) in O(n) space for invertible operations.
Pass `encoding="utf-8"` on every text open, because the default depends on the operating system.
Python reads and writes files with open(). Always use 'with open(...) as f:' for automatic cleanup. Modes: 'r' (read), 'w' (write/overwrite), 'a' (append).
Push the exponential part onto a small parameter k. Vertex cover of size at most k branches on one edge into two choices, giving at most 2^(k+1) - 1 nodes and O(2^k * m) time.
Search real numbers by halving an interval a fixed number of rounds, not until a tolerance is met, because floats far from 1 can be too far apart for a tolerance loop to ever finish.
Floyd-Warshall fills an all-pairs distance table with three nested loops, k outermost, in O(V cubed) time and O(V squared) space. A negative dist[i][i] marks a negative cycle.
for loops iterate over sequences (lists, ranges, strings), while loops repeat as long as a condition is True. break exits early, continue skips to the next iteration.
A generator uses yield instead of return to produce values lazily, one at a time. This keeps memory usage constant even for infinite or very large sequences.
Git is a distributed version control system that tracks changes through commits, branches, and merges — the universal tool for collaborative coding.
A remote is a named copy of the repository; `clone` copies it, `push` sends commits and `pull` fetches and merges.
The GIL (Global Interpreter Lock) lets only one thread run Python bytecode at a time — threads help I/O-bound work, multiprocessing helps CPU-bound.
A graph is a set of nodes connected by edges — represented as adjacency lists or matrices, traversed via BFS or DFS.
A greedy algorithm makes the best-looking choice at each step and never undoes it. It is correct only when some best answer contains the greedy choice and the rest is a smaller copy of the same problem.
A table with one cell per grid square, each built from the cell above and the cell to its left. It counts routes, handles blocked squares by holding 0, and finds minimum path sums in O(rows * cols).
A rule that turns a key into a whole number, the same number every time. The index is that number modulo the table size, so the key says where to look.
The structure behind a dictionary: the key is turned into a number that says which slot to look in, so a lookup is one jump rather than a scan of every key. A million keys take the same one jump.
A binary heap is an array-backed complete tree maintaining the parent-child order property, giving O(log n) push/pop and O(1) peek at the extremum.
A heapq heap is a plain list where heap[k] is at most heap[2k+1] and heap[2k+2]. Push and pop are O(log n), heapify is O(n), and pairs that can tie need a counter so the item is never compared.
A navigable graph links each vector to near ones, and a search walks greedily with a beam of width ef. HNSW stacks sparse layers on top so long jumps come first. It has no worst-case guarantee, and recall is measured.
Build a prefix code by repeatedly merging the two rarest trees with a heap, so common letters get short bit strings. Build cost is O(n log n) for n distinct letters.
HyperLogLog estimates how many different items a stream held from the longest run of leading zeros in their hashes, kept in m registers. Relative error is about 1.04 / sqrt(m), repeats cost nothing, and two sketches merge by taking the larger value in each register.
Conditional statements (if/elif/else) execute different code blocks based on boolean conditions, controlling the flow of a program.
Inheritance lets a child class reuse and extend a parent class. Polymorphism means the same method name behaves differently in different classes via method overriding.
Pass a collaborator such as a client into your code so a fake can replace it in tests.
Pass the client into your code so tests use a mock instead of calling the model.
The letter n is the number of values a program has to handle, and cost is counted in steps as a function of n, because steps do not depend on the machine the way seconds do.
A table with one cell per slice [i, j] of a sequence, filled by increasing slice length and built by splitting the slice at a point k. Burst balloons and palindrome cuts are examples; the usual cost is O(n^3).
Sort by end time and keep each interval that starts at or after the last kept end to pick the most non-overlapping intervals. Sort by start and stretch the last interval to merge overlaps. Both cost O(n log n).
An inverted file index clusters the vectors with k-means and, for a query, scans only the nprobe lists whose centers are closest to it.
JSON Lines is one JSON object per line: append to it, stream it lazily and lose at most one line to a crash.
Karatsuba multiplies two n-digit numbers with three half-size multiplications instead of four, using (a+b)(c+d) - ac - bd for the middle term. T(n) = 3T(n/2) + n gives about O(n^1.585) against O(n^2) at school.
A border is a piece of a string that is both a prefix and a suffix. The prefix function stores the longest border of every prefix, and KMP falls back along borders on a mismatch, so it never moves left in the text. Search is O(n + m) time and O(m) space because k rises at most once per letter.
Kruskal sorts the edges and keeps each one whose ends are in different Union-Find groups. Prim grows one tree from a start node with a heap of crossing edges, skipping stale entries. Both are O(E log V) time and O(V + E) space.
A lambda is a small anonymous function written in one line (lambda x: x * 2), useful as arguments to sort(), filter(), and map().
A singly linked list chains nodes via `next` pointers — O(1) insert at head, O(n) random access, and no contiguous memory required.
Common patterns include reversing in place by rewiring `next` pointers, detecting cycles with Floyd's tortoise-and-hare, and finding the middle with slow/fast pointers.
A list keeps spare capacity and grows it by a ratio r above 1, so appends are O(1) amortized and copy at most r/(r-1) pointers per append. A fixed step instead costs O(n) per append and O(n squared) overall.
Retry 429, 5xx and connection errors with backoff and the server's `retry-after`; 400, 401 and 404 are your bug.
The load factor is pairs divided by cells. When it passes a limit the table doubles and every pair is placed again, which costs O(n) once in a while and O(1) amortized per put.
`loc` selects by label and includes its end label; `iloc` selects by position and excludes its end.
Local search improves a valid answer by small changes (2-opt for TSP) until it reaches a local optimum with no proven ratio; simulated annealing sometimes accepts worse moves, with a probability that shrinks as a temperature falls.
Random-hyperplane hashing gives each vector a signature of sign bits, so vectors at a small angle share a bucket with high probability. Bits act as an AND and independent tables act as an OR.
log n is how many times you can cut n in half before nothing is left, so a thousand values need about 10 steps and a million about 20; doubling n adds just one step.
Expand outward from each of the 2n - 1 centers while the outer letters agree: O(n squared) time, O(1) space. Manacher's idea reuses mirrored radii inside the furthest palindrome to reach O(n).
An invariant is a sentence about your variables that is true before a loop, after every pass and when it stops; write it first, then write the loop to keep it true. For binary search it says the target, if present, lies between lo and hi.
The lower bound of x is the first index whose item is x or more, and the upper bound is the first index whose item is bigger than x; they are bisect_left and bisect_right, and their difference counts the copies of x.
An LSM tree buffers writes in a memtable, flushes immutable sorted runs, reads newest to oldest, hides deletes with tombstones, skips runs with Bloom filters, and merges runs by compaction at the price of write amplification.
Matplotlib is Python's foundational plotting library. Use plt.plot() for lines, plt.scatter() for relationships, plt.bar() for categories, plt.hist() for distributions, and plt.subplots() for multi-panel figures.
Max-flow pushes the bottleneck along augmenting paths in a residual graph whose backward edges undo earlier choices. Edmonds-Karp uses BFS paths for O(V times E squared) time, and the max-flow equals the min-cut.
Memoization caches function results by argument, turning exponential recursion (fib) into linear time — a one-line `@lru_cache` decorator handles it.
Merge sort halves the list, sorts each half recursively and merges the two sorted halves in one pass. It is always O(n log n), stable, and uses O(n) extra space.
Python uses the C3 linearization algorithm to flatten multiple inheritance into a deterministic lookup order, viewable via `Cls.__mro__`.
A spanning tree joins all V nodes of a connected graph with V-1 edges and no cycle. The minimum one has the smallest total weight, that weight is unique, and the cut property (the cheapest edge across any split of the nodes is safe to take) is why greedy algorithms find it.
NaN marks a missing cell; find it with `isna` and drop or fill it on purpose.
sklearn Pipelines chain preprocessing and modeling steps, preventing data leakage by ensuring transformers are fit only on training data. Use Pipeline([('scaler', StandardScaler()), ('model', RandomForest())]).
A module is a .py file you import to reuse code. Use import, from...import, and aliases (import numpy as np). Packages are directories with __init__.py.
Whether an object can be changed in place. Lists, dictionaries and sets can be; numbers, strings and tuples cannot — changing one of those always makes a new object and leaves the old one alone.
`namedtuple` builds a lightweight immutable class with named fields — same memory footprint as a tuple but accessible via `.field` instead of `[0]`.
Nearest neighbor search returns the k stored vectors closest to a query vector. Exact search scans all n vectors in O(n d) time, and approximate indexes trade a measured amount of recall for speed.
NumPy provides fast n-dimensional arrays and vectorized operations implemented in C. Whole-array operations run in compiled code, so they are typically much faster than the same work in a Python loop.
A NumPy array (ndarray) is a fixed-type, n-dimensional container for numerical data with fast vectorized operations, forming the basis of all scientific Python.
Arrays of different shapes combine by comparing shapes from the last axis, where the sizes must be equal or 1.
f is O(g) if from some size n0 on, f(n) is at most c times g(n): a ceiling. Omega is the matching floor, Theta is both (a tight bound), and little-o means f(n) divided by g(n) goes to zero. They describe a function, so O is not the same as worst case.
Python caches small integers (-5 to 256) and interned strings, so `is` sometimes returns True for equal values — always use `==` for equality.
A collision plan where each slot holds one pair, and a key whose home slot is taken tries other slots (linear probing tries the next one). A delete must leave a tombstone so lookups do not stop too early.
An operation counter plus a doubling test shows the growth rate (a factor of 4 per doubling means n squared). A seeded stress test compares the fast solution with a brute force on thousands of small random inputs and reports the smallest failing case.
Defining `__add__`, `__eq__`, `__lt__`, etc. lets your objects respond to `+`, `==`, `<` so custom types feel native to the language.
P is the decision problems solvable in polynomial time, and NP is those whose yes-answers can be checked in polynomial time from a certificate. P sits inside NP, whether they are equal is open, and NP-complete means NP-hard and in NP.
Pandas provides DataFrames — labeled 2D tables for data manipulation. Load CSVs, filter rows, group and aggregate, handle missing data, and perform exploratory analysis.
`apply` runs a function across rows or columns of a DataFrame — flexible but slow; prefer vectorized operations when the same logic is expressible.
`groupby` splits rows by a column and summarises each group; the mean of a 0/1 column is a rate.
`pd.merge` joins DataFrames on keys with inner, outer, left, or right semantics — the SQL JOIN of pandas, with `on`, `left_on`, and `right_on` controls.
`pivot_table` reshapes long data into wide summaries by grouping on index/columns and aggregating values — the spreadsheet pivot, but scriptable.
Pandas time series tools include `DatetimeIndex`, `resample` for downsampling, `rolling` windows, and timezone-aware arithmetic for clean temporal analysis.
Parquet is a binary, column-oriented file format that keeps column types and needs `pyarrow` or `fastparquet`.
Path compression points every item on a find path straight at the root, and union by rank hangs the shorter tree under the taller. Together they make each Union-Find operation O(alpha(n)) amortized, where the inverse Ackermann function alpha acts like a constant.
`pathlib.Path` provides object-oriented filesystem paths with operator overloading (`p / 'sub'`) and methods like `.read_text()`, `.glob()`, `.exists()`.
A peak is a value bigger than both neighbours; comparing a[mid] with a[mid + 1] shows which half must hold one, so a peak is found in O(log n) without sorted data.
PEP 8 is Python's official style guide — 4-space indents, snake_case for functions, PascalCase for classes, 79-char lines, and two blank lines between top-level defs.
`pickle.load` can run code, so unpickle only data you wrote yourself.
pip installs third-party packages from PyPI. Virtual environments (python -m venv) isolate project dependencies. requirements.txt lists exact package versions for reproducibility.
A prefix-sum list stores the running total up to each position, so any range sum is one subtraction after O(n) set-up. With a dict of earlier totals it also counts the subarrays that add up to k in one pass.
print() outputs text to the console, and the Python REPL (Read-Eval-Print Loop) lets you run code interactively line by line.
A priority queue dequeues the highest-priority element first; Python's `heapq` implements a min-heap, so negate keys or use `(-priority, item)` for max-heap behavior.
The `@property` decorator turns a method into a computed attribute, letting you add getters, setters, and validation without breaking the public API.
A protocol is an informal interface defined by which dunder methods an object implements — anything with `__iter__` is iterable, no inheritance required.
To prove f = O(g), choose a constant c, solve f(n) at most c times g(n) for n to get n0, and state both. To disprove it, assume some c and n0 work and show a larger n breaks it, as with n squared against c times n.
Cut a branch the moment it provably cannot reach a good answer, so nothing below it is visited. It lowers the typical cost a great deal and rarely changes the exponential worst case.
The subset-sum and knapsack DPs cost O(n * T) and O(n * W), polynomial in the value of the numbers but exponential in their bit length, so one more digit in T means about ten times more work.
Pydantic validates and parses data using Python type hints — define a `BaseModel` subclass and bad input raises a clear `ValidationError`.
`pyproject.toml` records what you asked for and `uv.lock` records the exact versions; commit both, never `.venv`.
Pytest is the de-facto Python test framework — write plain `test_*` functions with `assert`, run `pytest`, and get rich failure diffs for free.
`pytest-cov` measures which lines your tests execute — aim high but remember coverage proves code ran, not that it's correct.
Fixtures are reusable setup functions decorated with `@pytest.fixture` — declare them as test arguments and pytest injects them with proper scoping and teardown.
`@pytest.mark.parametrize` runs the same test against many input/expected pairs — one function generates dozens of test cases with clear failure isolation.
Python supports +, -, *, /, // (floor division), % (modulo), and ** (exponentiation) operators for numerical computation.
Async lets one thread juggle many I/O-bound tasks via cooperative `await` points — great for network calls, useless for pure CPU work.
Python compiles source to bytecode instructions executed by the CPython VM — inspect with `dis.dis(func)` to see what your code actually runs.
A class is a blueprint for creating objects, defined with class keyword. __init__ initializes attributes, self refers to the current instance, and methods define behavior.
Build CLIs with `argparse` (stdlib) or `click`/`typer` for richer ergonomics — parse flags, validate input, and expose subcommands like `git` does.
Python talks to databases via DB-API 2.0 drivers — always use parameterized queries to prevent SQL injection, and connection pools for concurrent access.
A dictionary maps keys to values for O(1) lookup. Created with {key: value} syntax, accessed with dict[key] or dict.get(key, default).
Functions are reusable code blocks defined with def, accepting parameters and returning values. They support default args, *args, and **kwargs.
Python uses reference counting plus a cyclic garbage collector to free unused objects — the `gc` module exposes tuning and inspection hooks.
Integration ties pieces together — data layers, APIs, CLIs, tests, and deploys — so individually correct modules form a working, observable system.
An ordered collection you can change in place — add, remove or replace items. Written in square brackets, like [1, 2, 3], and reached by position starting at 0.
The `logging` module provides leveled, configurable output (DEBUG, INFO, WARNING, ERROR) — never use `print` in production code; loggers are filterable and routable.
Python objects live on the heap and are reclaimed by reference counting plus a cyclic garbage collector that handles reference cycles.
`multiprocessing` spawns separate processes that bypass the GIL — true parallel CPU work at the cost of inter-process communication overhead.
Packaging turns a project into a `pip install`-able distribution via `pyproject.toml` — declare dependencies, entry points, and metadata for PyPI.
Profiling identifies slow code with `cProfile`, `timeit`, or `line_profiler` — measure before optimizing, because intuition about hot paths is usually wrong.
Good project design separates concerns into modules, keeps functions small and pure, isolates I/O from logic, and writes for the next reader (often you).
A clean layout uses `src/` for code, `tests/` for tests, `pyproject.toml` for config, and a virtual environment to isolate dependencies per project.
Python's `re` module compiles regular expressions for matching, searching, and substitution — use raw strings (r"...") to avoid escaping backslashes.
The REPL is an interactive Python shell where you type code, it runs immediately, and results are printed — perfect for experimentation.
The `sqlite3` module ships with Python — connect, execute parameterized SQL with `?` placeholders, and commit changes; perfect for embedded storage.
The `threading` module runs tasks concurrently in one process — bound by the GIL, so use threads for I/O waits, not CPU-bound number crunching.
Python's core types are int, float, str, bool, and None. Python is dynamically typed — variables can change type at runtime.
A variable is a name that refers to a value stored in memory, created by assignment (x = 42) with no type declaration needed.
A queue is a First-In-First-Out collection. enqueue() adds to the back, dequeue() removes from the front. Used for BFS, task scheduling, and message processing.
Quick sort partitions the list around a pivot so smaller items sit left and larger items right, then sorts each side. It is O(n log n) on average and O(n^2) in the worst case; a random pivot makes the worst case unlikely.
Quickselect finds the k-th largest by partitioning around a pivot and keeping only the side that holds the answer. It is O(n) expected with a random pivot and O(n^2) in the worst case; median of medians gives O(n) worst case with large constants.
A seeded `default_rng` makes random draws repeatable.
A range query asks for a sum or minimum over a stretch of an array. Three costs describe any answer: build, query and update. Choose the structure by whether the data changes and whether the operation is invertible, idempotent or merely associative.
The limit on n tells you which growth rates fit a budget of about ten million simple steps: n! up to about 10, 2^n up to about 20, n cubed up to a few hundred, n squared up to a few thousand, n log n up to around 100,000 and more, and one pass beyond that. The estimate assumes simple steps and worst-case input.
Recall is the share of the true top-k neighbors that an approximate search returned. Measure it against an exact scan on held-out queries, and tune the dial (nprobe, ef, bits and tables) for the cheapest setting that meets the target.
Recover the actual route or subsequence, not just its value, by walking back through the table to the neighbour each value came from, or by storing a parent array while filling.
A recurrence T(n) = a T(n/b) + f(n) writes the cost of a recursive function from its code: a calls, each on n/b of the input, plus f(n) work to divide and combine (copies from slices included). Solve it by counting the work on each level of the recursion tree.
Recursion solves a problem by calling the same function on smaller subproblems — every recursion needs a base case to stop the call stack.
A BST with a color bit per node: the root is black, a red node has no red child, and every downward path has the same number of black nodes. That caps the height at 2 log2(n + 1) with at most two rotations per insert.
A reduction turns every input of problem A into an input of problem B in polynomial time so the answers match, which makes B at least as hard as A. To prove a new problem hard, reduce a known hard problem to it.
A name in Python points at an object; it does not contain it. Assignment moves the name, it never copies the object — which is why two names can change together.
A regex engine that fails a match backs up and tries other ways; nested quantifiers such as `(a+)+b` give it exponentially many ways on a non-matching input, so write unambiguous patterns and test them against bad input.
Parentheses create capture groups whose matches are retrieved via `match.group(n)` or named with `(?P<name>...)` — backreferences enable matching repeats.
A lookahead such as `(?=...)` checks what comes next without consuming it, and `(?!...)` is the negative form, so a pattern can require or forbid a following piece of text without including it in the match.
Common regex patterns: \d for digits, \w for word chars, + and * for quantifiers, ^$ for anchors, and [] for character classes.
A requirements file lists one `name==version` per line and installs with `pip install -r` or `uv pip install -r`.
Reservoir sampling keeps k items fairly from a stream of unknown length in one pass and O(k) space: keep the first k, then let item i replace a random slot with probability k/i. Every item seen so far is in the sample with probability k/i.
REST APIs expose resources over HTTP using verbs (GET, POST, PUT, DELETE) and JSON payloads — stateless, cacheable, and the lingua franca of web services.
A polynomial hash can slide along a text in O(1) per step by removing the front letter and adding the new one. Rabin-Karp compares hashes first and letters only on a match, so it is expected O(n + m) if hashes act randomly, and O(n times m) in the worst case.
sklearn provides a consistent fit/predict/score API for hundreds of ML algorithms. The workflow: load data, train_test_split, fit a model, predict, and evaluate with metrics.
Python resolves names in Local, Enclosing, Global, then Built-in order; use `nonlocal` to rebind enclosing names and `global` for module-level ones.
Find the pivot (the smallest value) with the test 'item is at most the last item', then search the list as if it were sorted using index (v + pivot) % n; repeated values break the test and can cost O(n).
A segment tree stores the answer for every stretch in a tree of halves. Any associative operation gets O(log n) point update and range query, because a query splits into at most about four nodes per level; lazy tags extend it to range updates in O(log n).
A collision plan where each bucket holds a list of pairs, so keys that land on the same index share the list. Put, get and delete walk one short chain, which is O(1) on average.
A collection that holds no duplicates and keeps no order. Checking whether something is in a set is one jump rather than a search, which is what it is for.
Test, set, clear and toggle bit i with a one-bit mask 1 << i. x & (x - 1) clears the lowest set bit and x & -x isolates it, which gives the power-of-two test and a popcount that runs once per set bit.
A skip list is a sorted linked list with express lanes whose node heights come from independent coin flips. Search and insert cost O(log n) expected and space is O(n) expected, with no rotations.
A sliding window keeps a running answer for the values between two markers. A fixed window adds one value and drops one per move; a variable window grows on the right and shrinks on the left, and its markers only move forward, so the whole pass is O(n).
Guess a bound for a recurrence such as T(n) = 2T(n/2) + n, then prove it by induction, checking the first case. The guess n log n works with c = 2 starting at n = 2; a guess of c times n is too low.
Bubble, selection and insertion sort are O(n²); merge sort is O(n log n), stable, with O(n) space; quick sort is O(n log n) on average and O(n²) at worst; Python's sorted is Timsort.
Space counts extra memory beyond the input. An in-place algorithm needs O(1) extra cells, and the recursion stack counts: a recursion n calls deep uses O(n) space, one that halves its input uses O(log n).
A sparse table stores the minimum of every block whose length is a power of two, in O(n log n) time and space. A range minimum is two overlapping block lookups, O(1), which is safe only for idempotent operations such as min, max and gcd on data that never changes.
SQLAlchemy is Python's premier ORM — define models as classes, query with Pythonic expressions, and switch databases without rewriting your data layer.
Cut the array into blocks of about sqrt(n) values and store one answer per block. A point update is O(1) and a range query reads at most about 3 sqrt(n) cells, trading speed for very simple code and support for odd operations.
A sort is stable if equal items keep their original order, and in place if it needs only a small, fixed amount of extra memory. Insertion, merge and Timsort are stable; selection, quick and heap sort are not.
A stack is a Last-In-First-Out collection. push() adds to the top, pop() removes from the top. Used for DFS, undo/redo, bracket matching, and function call tracking.
The staging area (index) holds the changes chosen for the next commit; `git add` fills it and `git commit` saves it.
Results go to stdout and diagnostics go to stderr, so a pipe sees only the result.
A stream is a context manager whose `text_stream` is a generator of text pieces.
Text. A Python string cannot be changed in place, so every join or replacement builds a new one — which is why adding to text in a loop is slow and join() is not.
An SCC is a largest group of vertices in a directed graph that all reach each other. Kosaraju finds them in O(V + E) with a finishing-order pass and a second DFS on the reversed graph, and the components form a DAG.
Python 3.10's `match`/`case` deconstructs values by shape — matching literals, sequences, mappings, and class patterns with optional guards.
Ask for JSON, parse it, validate it and repair once; valid JSON is not the same as a valid answer.
A suffix array lists the start indexes of all suffixes of a fixed text in sorted order. All suffixes that begin with a pattern form one block, so binary search answers each query in O(m log n) plus the hits.
Python searches `sys.path` in order, so a file of your own named like a package hides the real package.
`str` holds Unicode code points while `bytes` holds raw 8-bit data; convert between them with `.encode('utf-8')` and `.decode('utf-8')` explicitly.
`if __name__ == "__main__":` keeps demo code from running when a file is imported.
`csv.DictReader` and `DictWriter` handle quoted commas; every value is a string and files are opened with `newline=''`.
Design any dynamic program by answering five questions in order: what one cell means (state), how a cell is built from smaller ones (transition), which cells are known (base case), in what order to fill them, and which cell holds the answer.
A dict lookup checks identity, then the stored hash, then ==. Equal keys must have equal hashes, and a stored key must never change its hash, or the entry is still counted but no lookup can find it.
For T(n) = a T(n/b) + O(n^d), compare a with b^d: if a is bigger the leaves dominate and the cost is n^(log_b a); if equal every level costs the same and the cost is n^d log n; if smaller the top level dominates and the cost is n^d. It does not cover uneven pieces, shrinking by subtraction, or an f(n) that is not a plain power.
Each comparison is a yes or no question, so k comparisons tell apart at most 2^k orders. A sort must tell apart n! orders, so every comparison sort needs at least log2(n!) comparisons, which grows like n log n.
Restate the problem, work examples by hand, write a brute force, find its bottleneck (the question it repeats), improve it with the technique that answers that question, then test edge cases against the brute force as an oracle.
Timsort finds runs, extends short ones by binary insertion, merges neighbors in balanced order, and gallops over streaks, so it is O(n log n) worst case, O(n) on one run, stable, and uses O(n) extra space.
Python's sorted and list.sort use Timsort: stable, O(n log n) in the worst case, and n - 1 comparisons on sorted input. key= gives the value to sort by, and a tuple key breaks ties.
Cost is input tokens and output tokens times a price you look up from the provider.
A topological sort puts the vertices of a DAG in a line so every arrow points forward. Kahn's algorithm repeatedly takes vertices of in-degree 0; a result shorter than the vertex count means a cycle. O(V + E).
A rotation changes three pointers so a child takes its parent's place while the left-to-right order of values stays the same. LL and RR imbalances need one rotation, LR and RL need two.
In-order yields BST values sorted, pre-order copies/serializes the tree, post-order frees/evaluates bottom-up, and level-order (BFS) walks tier by tier.
A trie (prefix tree) stores strings as paths from the root, giving O(k) lookup and prefix matching for autocomplete and spell-check.
A group of values in round brackets, like (3, 4). Once it exists its slots cannot be pointed at anything else, which is why a tuple can be a dictionary key and a list cannot.
The two-pointer technique walks a sequence with two indices, from opposite ends or both moving the same way (a read pointer and a write pointer), to solve pair-sum, palindrome and in-place filtering problems in O(n) time.
Type hints annotate function signatures (def add(a: int, b: int) -> int) and variables. They are not enforced at runtime but help tools like mypy catch type errors early.
Undo an unsaved edit with `git restore` and a saved commit with `git revert`; `git reset --hard` discards uncommitted work for good.
Union-Find (Disjoint Set Union) tracks connected components with near-O(1) union and find operations using path compression and rank-based merging.
assert statements verify conditions are True, raising AssertionError if False. Group tests in functions, test edge cases, error paths, and expected outputs to catch bugs early.
An upper bound on a problem comes from an algorithm; a lower bound argues about every algorithm. Finding the maximum needs n - 1 comparisons because each non-maximum must lose once and a comparison makes one loser; sorting needs log2(n!) comparisons.
uv is a Python package and project manager: `uv venv`, `uv pip install`, `uv init`, `uv add`, `uv run` and `uv sync`.
Quantization stores each number of a vector in fewer bits. Ranking with the compressed vectors and re-ranking a short list with the full ones recovers most of the lost recall.
A venv isolates a project's Python interpreter and packages so dependencies for one project never collide with another or with the system Python.
The walrus operator assigns and returns a value in the same expression, letting you write `while (line := f.readline()):` without repeating reads.
Append a checksummed record of each change to a log and make it durable before changing memory. After a crash, replay the log and stop at the first damaged record.
a ^ a is 0 and a ^ 0 is a, and XOR ignores order and grouping, so equal pairs cancel. XOR of a whole list finds the one unpaired value in O(n) time and O(1) space.
Adam combines momentum with per-parameter adaptive learning rates, making it one of the most popular and robust optimizers for deep learning.
Bayes' theorem lets you update the probability of a hypothesis as you observe new evidence: P(H|E) = P(E|H) * P(H) / P(E).
The chain rule computes the derivative of a composite function by multiplying the derivatives of each nested function, enabling backpropagation.
Conditional probability is the likelihood of an event occurring given that another event has already occurred, written P(A|B).
A confidence interval is a range of values that, with a specified probability, contains the true population parameter being estimated.
Convergence occurs when a training algorithm's loss stabilizes at a minimum, meaning further updates produce negligible improvement.
Cosine similarity measures the angle between two vectors, giving a value from -1 (opposite) to 1 (identical direction) regardless of magnitude.
Cross-entropy measures the difference between two probability distributions and is the standard loss function for classification tasks.
A derivative measures the instantaneous rate of change of a function with respect to its input.
Descriptive statistics summarize a dataset with measures of center (mean, median, mode) and spread (standard deviation, variance) to reveal its key characteristics.
The dot product multiplies corresponding elements of two vectors and sums the results, measuring how aligned they are.
An eigenvalue is the scalar factor by which a matrix stretches its corresponding eigenvector without changing its direction.
Entropy measures the average amount of surprise or uncertainty in a probability distribution; higher entropy means more unpredictability.
Expected value E[X] is the probability-weighted average of all possible outcomes of a random variable — the long-run average if the experiment is repeated forever.
Gradient descent iteratively adjusts parameters in the opposite direction of the gradient to minimize a loss function.
A gradient is a vector of partial derivatives pointing in the direction of steepest increase of a multivariable function.
Hypothesis testing is a statistical method that uses sample data to evaluate whether a claim about a population parameter is likely true or false.
KL divergence quantifies how much one probability distribution differs from a reference distribution; it is always non-negative and zero only when the distributions match.
The learning rate controls the step size taken during each gradient descent update; too large causes overshooting, too small causes slow convergence.
A linear transformation maps vectors to vectors while preserving addition and scalar multiplication, and every such map can be represented as a matrix.
A local minimum is a point where the loss is lower than all nearby points but not necessarily the lowest overall; momentum and noise help escape them.
A loss function measures how far a model's predictions are from the true values, providing the signal that gradient descent uses to improve.
The loss landscape is the surface formed by plotting the loss function over all possible parameter values; gradient descent navigates this surface toward minima.
A matrix is a 2D grid of numbers that can represent data, transformations, or systems of equations.
Matrix multiplication combines two matrices by computing dot products of rows and columns; it is the core operation in neural network forward passes and attention.
Momentum accelerates gradient descent by accumulating a running average of past gradients, helping escape local minima and smooth noisy updates.
The normal (Gaussian) distribution is a bell-shaped curve defined by its mean and standard deviation, appearing ubiquitously in nature and ML due to the Central Limit Theorem.
A p-value is the probability of observing results at least as extreme as the data, assuming the null hypothesis is true.
A partial derivative measures how a function changes when only one of its input variables changes while the others are held fixed.
Probability quantifies how likely an event is to occur, expressed as a number between 0 (impossible) and 1 (certain).
A random variable is a function that maps outcomes of a random experiment to real numbers, enabling mathematical analysis of uncertainty.
SVD decomposes any matrix into three simpler matrices (U, Sigma, V-transpose), revealing its fundamental structure and enabling dimensionality reduction.
Stochastic calculus extends derivatives to random processes — Brownian motion, Itô integrals, and stochastic differential equations. The math diffusion models, flow matching, and score-based generative models all live in.
Variance Var(X) measures how spread out a random variable's outcomes are around its expected value, computed as E[(X - E[X])^2].
A vector is an ordered list of numbers representing magnitude and direction in n-dimensional space.
Turning category labels into numbers so a model can use them, without implying an order or leaking the target.
Reading only the rows that changed in a source database instead of re-copying the whole table.
Class imbalance (e.g., 99% non-spam vs 1% spam) makes accuracy misleading — a model predicting the majority class always wins 99% but finds zero spam.
The relationship between inputs and the target changes, so the same input now deserves a different answer.
The input distribution changes while the input-to-output relationship stays the same.
Cross-validation rotates through multiple train/test splits and averages the results, giving a more reliable estimate of model performance.
Data augmentation artificially increases training data by applying transformations like flipping, rotating, or adding noise to existing samples.
Getting data out of APIs, databases, files and streams into your pipeline without losing or duplicating rows.
Data leakage occurs when information from outside the training set bleeds into the model, causing overly optimistic performance estimates that collapse in production.
A data pipeline is a series of automated steps that ingest, clean, transform, and deliver data from raw sources to an ML-ready format.
Data quality encompasses accuracy, completeness, consistency, and timeliness; poor data quality is the most common cause of ML project failure.
Asserting schema and value expectations on every batch before it reaches a model.
A table of facts in which each row is one example and each column is one kind of fact about it.
A distribution describes how the values of a variable are spread or clustered, such as normal (bell curve), uniform, or skewed shapes.
EDA is the process of visually and statistically summarizing a dataset to discover patterns, anomalies, and relationships before modeling.
Feature engineering transforms raw data into informative input features that help ML models learn patterns more effectively.
Mapping any number of categories into a fixed number of buckets with a hash function, accepting collisions.
Feature scaling normalizes or standardizes numerical features to a common range so that no single feature dominates the learning process.
A feature vector is the numerical representation of a single data sample, with each dimension corresponding to a measured feature.
The label is the column you want to guess; the features are the columns you guess it from. The label is never an input.
Row formats (CSV, JSON) versus columnar formats (Parquet), and why a query that needs few columns prefers columnar.
An anomaly detector that isolates points with random splits; points isolated in few splits are outliers.
Splitting data into k parts and rotating which part is held out, then averaging the scores.
Using earlier values of a series (t-1, t-7) as inputs for the value at time t.
An anomaly score that compares a point's local density with its neighbours' density.
Distance that accounts for scale and correlation between features, so it catches combinations that are jointly rare.
A score for how much knowing a feature reduces uncertainty about the target, including nonlinear links.
An outer loop to estimate performance and an inner loop to tune, so tuning never sees the outer test fold.
One-hot encoding converts categorical variables into binary vectors with one 1 and the rest 0s, making categories usable by numerical models.
Finding points that do not belong, then deciding to drop, cap, transform or keep them.
Oversampling duplicates or synthesizes minority-class examples to balance the training set — boosts recall on the rare class but risks overfitting.
A binned score of how far today's feature distribution is from a reference; 0.1 and 0.25 are common rule-of-thumb alert levels.
Counting rows and empty cells, summarising a column and comparing groups of rows, by hand and in a few lines of Python.
A wrapper method that repeatedly fits a model and drops the weakest features.
Summary statistics (mean, std) over the last k steps, computed only from the past.
Chaining preprocessing and a model so every step is fitted on training rows only inside each fold.
SMOTE (Synthetic Minority Oversampling Technique) creates new minority-class samples by interpolating between existing ones in feature space, not duplicating them.
K-fold that keeps the class proportions the same in every fold.
The smallest, biggest, mean and median of a column, each describing it in a different way.
Replacing a category with the average target for that category, computed out of fold so a row never sees its own label.
Data where row order matters, so splits, features and checks must respect time.
Splitting data into separate training, validation, and test sets ensures the model is evaluated on data it has never seen during training.
Undersampling drops majority-class examples to match the minority count — fast and simple, but throws away potentially useful data.
Classical ML + Deep Learning
The bias-variance tradeoff describes how decreasing a model's bias (underfitting) typically increases its variance (overfitting), and vice versa.
Boosting sequentially trains weak learners, each focusing on the mistakes of the previous one, to build a strong ensemble model.
A supervised job where the answer is a label from a short list, such as cat or dog, or spam or not spam.
Clustering groups similar data points together without labels, revealing natural structure in the data.
A confusion matrix is a table showing true positives, false positives, true negatives, and false negatives for a classifier.
A decision tree with a single yes or no question; the best question is the one with the fewest mistakes on the known rows.
A decision tree splits data into branches using yes/no questions on features, creating an interpretable flowchart for prediction.
Dimensionality reduction compresses high-dimensional data to fewer dimensions while keeping its essential structure — fights the curse of dimensionality and enables visualization.
ElasticNet blends L1 and L2 penalties, getting Lasso's sparsity and Ridge's stability — preferred when correlated features confuse pure Lasso.
The straight-line distance between two points, the square root of the summed squared gaps; it depends on the units of every feature, so features are usually rescaled first.
The F1 score is the harmonic mean of precision and recall, providing a single metric that balances both.
Feature selection picks the most predictive subset of inputs — reducing overfitting, speeding training, and making models more interpretable.
Choose the projection that maximises between-class scatter over within-class scatter.
Generalization is a model's ability to perform well on unseen data, not just the training set; it is the ultimate goal of machine learning.
A hyperparameter is a setting chosen before training (e.g., learning rate, batch size, number of layers) that controls the training process but is not learned from data.
K-means partitions data into k clusters by iteratively assigning points to the nearest centroid and recomputing centroids.
KNN classifies a data point by a majority vote of its k closest neighbors in feature space, requiring no training phase.
Laplace smoothing adds a small count (alpha) to every feature frequency to prevent zero probabilities from unseen features destroying the classification.
Lasso (L1 regularization) penalizes the sum of |coefficients|, driving some to exactly zero — it does both shrinkage AND feature selection in one step.
Classify with one shared covariance per class, giving a straight boundary; also a supervised projection to at most C-1 directions.
Linear regression fits a straight line (or hyperplane) to data by minimizing the sum of squared errors between predictions and targets.
Logistic regression applies a sigmoid function to a linear model to output probabilities for binary classification.
A model is a rule with adjustable knobs that turns something you know into a guess about something you do not; training sets the knobs from rows with known answers.
The average size of the miss between guesses and true answers, ignoring direction; a small value means the guesses are close on average.
Parameters are the numbers inside a model that training adjusts, such as the slope and start of a straight-line rule or the dials of a large language model.
Naive Bayes is a probabilistic classifier that applies Bayes' theorem with the assumption that features are conditionally independent given the class label.
Overfitting occurs when a model memorizes training data (including noise) so well that it fails to generalize to new data.
Precision measures how many positive predictions were correct; recall measures how many actual positives were found.
PCA reduces dimensionality by projecting data onto the directions (principal components) that capture the most variance.
Give each class its own covariance so the decision boundary curves.
A random forest trains many decision trees on random subsets of data and features, then averages their predictions to reduce overfitting.
A supervised job where the answer is a number, such as a price, a rainfall amount or a count of cones sold.
MAE, MSE, RMSE, and R-squared each measure regression error differently — RMSE punishes large errors, MAE treats all errors equally, R-squared shows variance explained.
Regularization adds a penalty term to the loss function (L1, L2) to discourage overly complex models and reduce overfitting.
Ridge (L2 regularization) penalizes the sum of squared coefficients, shrinking them smoothly toward zero but never eliminating any — keeps all features.
ROC-AUC measures a classifier's ability to distinguish between classes across all threshold values; 1.0 is perfect, 0.5 is random.
A series whose mean and spread do not drift over time, which many methods assume.
Supervised learning trains a model on labeled input-output pairs so it can predict the output for new, unseen inputs.
An SVM finds the hyperplane that maximizes the margin between classes, using the kernel trick to handle non-linear boundaries.
t-SNE projects high-dimensional data to 2D/3D by preserving local neighborhoods — great for visualization, but distances between clusters aren't meaningful.
UMAP reduces dimensions while preserving both local and some global structure — faster than t-SNE and often produces more meaningful cluster separations.
Underfitting occurs when a model is too simple to capture the underlying patterns in the data, leading to poor performance even on training data.
Unsupervised learning finds hidden patterns or groupings in data without any labeled examples.
Three neurons in two layers (OR, AND, then a neuron that reads both) compute exclusive-or, which no single neuron can.
Activation functions introduce nonlinearity into neural networks, enabling them to learn complex patterns beyond simple linear mappings.
Adam keeps a running mean and running squared mean of each gradient and uses them to give every parameter its own step size.
Attention computes a weighted sum of values where the weights reflect how relevant each element is to the current query.
Attention weights are the softmax-normalized scores that determine how much each token attends to every other token, forming an interpretable attention pattern.
Autograd records each operation in a graph and replays the chain rule backwards to get every gradient.
Backpropagation computes gradients of the loss with respect to each weight by applying the chain rule backwards through the network.
Batch normalization normalizes layer inputs across a mini-batch, stabilizing training and allowing higher learning rates.
Batch size is the number of training examples processed together in one gradient update; smaller batches add noise that can help generalization.
Beam search keeps the k best partial outputs at every step instead of committing to the single most likely token.
A bias is a learnable constant added to the weighted sum in a neuron, allowing the activation function to shift left or right for better data fit.
Convolution applies a small filter to an input by sliding it across the data and computing element-wise products, producing a feature map.
A CNN uses learnable filters that slide across spatial data (like images) to detect local features such as edges, textures, and shapes.
The architectural side of diffusion models — U-Net backbones, time-conditioning blocks, attention placement, and the engineering tricks that make denoisers actually train at scale.
Distributed training splits a model or its data across many GPUs (data, tensor, pipeline and sequence parallelism, plus sharded optimizer state) because one device cannot hold or process a large model alone.
Dropout randomly deactivates a fraction of neurons during training, forcing the network to learn redundant representations and reducing overfitting.
The encoder-decoder architecture uses an encoder to build a contextual representation of the input and a decoder to generate the output sequence.
An epoch is one complete pass through the entire training dataset; models typically train for many epochs until the loss converges.
Fine-tuning unfreezes some or all layers of a pretrained model and trains them on new data with a small learning rate.
Focal loss down-weights easy examples with a (1-p)^gamma factor, focusing training on hard, misclassified samples — designed for extreme class imbalance.
The forward pass propagates input data through each layer of a neural network to produce a prediction.
GANs train a generator-discriminator pair adversarially; VAEs learn an encoder-decoder with a KL-regularized latent prior. The two pre-diffusion deep generative families and the architectures the generative-AI track builds on.
A gradient check nudges one weight a tiny bit up and down, recomputes the loss each time, and compares the change divided by the gap with the gradient from backprop. If they agree to many digits, the backward pass matches the loss as written.
A GNN updates each node by combining messages from its neighbours, repeated for several rounds.
Layer normalization normalizes activations across the feature dimension for each sample, stabilizing training in transformers where batch sizes may vary.
Training is a loop: guess, measure how wrong, try a tiny nudge to find the slope, move the dial against it, repeat.
Warmup raises the learning rate from near zero over the first steps so early, noisy updates do not wreck training.
An LSTM (Long Short-Term Memory) uses forget, input, and output gates to selectively remember or discard information across long sequences.
Mamba is a state-space model whose update rule depends on the current token, so it can choose what to remember in linear time.
MSE squares residuals before averaging — it penalizes large errors disproportionately, making outliers dominate the loss for regression tasks.
Each node sends a message along its edges, receives its neighbours' messages, and updates its own vector from them.
Mixture of Experts routes each input to a subset of specialized sub-networks (experts), enabling massive model capacity without proportional compute cost.
The ML decision framework guides when to use deep learning versus classical ML based on data size, interpretability needs, and compute budget.
A neural network is a layered system of interconnected nodes (neurons) that learns to map inputs to outputs by adjusting connection weights.
A neuron multiplies each input by a weight, adds the products and a bias, and answers 1 only if the total is greater than 0.
Detection predicts a class and a box for every object in an image, not one label for the whole image.
A perceptron is the simplest neural network: a single neuron that computes a weighted sum of inputs, adds a bias, and applies a threshold.
Pooling reduces the spatial dimensions of feature maps by summarizing local regions (e.g., max pooling takes the largest value in each window).
In attention, each token is projected into query (what am I looking for?), key (what do I contain?), and value (what information do I carry?) vectors.
An RNN processes sequential data by maintaining a hidden state that captures information from previous time steps.
ReLU (Rectified Linear Unit) outputs the input directly if positive, otherwise zero; it is the most widely used activation function in deep learning.
A residual (skip) connection adds a layer's input directly to its output, enabling gradient flow through very deep networks and preventing degradation.
A residual block adds its input to its output, so gradients have a short path and very deep networks can be trained.
Self-attention lets each token in a sequence attend to every other token, capturing context-dependent relationships within the same input.
The training signal is built from the data itself, for example a masked piece to predict, so no human labels are needed.
The sigmoid function squashes any input to a value between 0 and 1, making it useful for probability outputs and gating mechanisms.
Softmax converts a vector of raw scores (logits) into a probability distribution that sums to 1, used as the final layer in classification and attention.
A state space model processes sequences by maintaining a compressed hidden state that evolves linearly, enabling efficient long-range dependency modeling.
The step is the step size times the slope; too small is slow, too big overshoots the bottom and can run away.
A tensor is a multidimensional array with a shape, a dtype and a device, and it can record the operations applied to it.
Multi-dimensional arrays plus automatic differentiation, the base of every deep-learning framework.
Most broken training code goes wrong in four places: the wrong axis or shape, a mean used where a sum was meant (or the reverse), a number that overflows, and a layer left in the wrong mode (batch norm and dropout differ between training and evaluation).
The training loop repeatedly performs forward pass, loss computation, backpropagation, and parameter update until the model converges.
Transfer learning reuses a model pretrained on a large dataset and adapts it to a new, often smaller, task-specific dataset.
A U-Net is an encoder-decoder architecture with skip connections that is the standard backbone for noise prediction in diffusion models.
When each layer shrinks the signal, gradients reaching early layers become tiny and those layers stop learning.
A weight is a learnable parameter in a neural network that scales an input signal; training adjusts weights via gradient descent to minimize the loss.
A weight says how much one input counts; the bias is a fixed number added to every total, setting how much evidence the neuron needs.
Transformers + Generative AI
Activation patching copies an internal activation from one run into another to test whether that part of the model causes a behaviour.
Agentic evaluations score a model on multi-step tasks with tools, judging the final outcome and the steps taken.
Alignment is the process of shaping a model's outputs to match human values, intent, and safety constraints — typically via RLHF, DPO, or constitutional methods.
Attention efficiency covers the tricks that make attention affordable at long context: FlashAttention, grouped-query attention, the KV cache, paged attention and sliding windows.
Each word scores every word it can see, a softmax turns the scores into shares that add up to 100%, and the word's new summary is a blend of what it saw weighted by those shares.
Autoregressive generation produces output one token at a time, conditioning each new token on all previously generated tokens.
A benchmark saturates when top models score so close to the maximum that it can no longer tell them apart.
BERT is a transformer encoder pretrained with masked language modeling that produces deep bidirectional representations for understanding tasks.
BPE iteratively merges the most frequent pair of tokens to build a vocabulary that balances character-level and word-level granularity.
Causal masking prevents each token from attending to future tokens, ensuring the model generates text left-to-right without peeking ahead.
Chain-of-thought prompting encourages a model to reason step-by-step before answering, dramatically improving performance on math, logic, and multi-step tasks.
CLIP aligns text and image embeddings in a shared space using contrastive learning, enabling zero-shot classification from text descriptions alone.
Code LLMs are language models trained heavily on source code, so they can complete, explain and fix programs.
Constitutional AI aligns a model with a written list of principles: the model critiques and revises its own outputs, and AI-generated preference labels replace most human labelling.
The context window is the maximum number of tokens a model can process at once; longer contexts require more memory and compute due to attention's quadratic cost.
Contrastive learning trains embeddings by pulling matched pairs together and pushing mismatched pairs apart — no labels needed, just positive/negative pairs.
The simplest language model keeps a tally of which word followed which and turns the counts into chances for the next word, but it sees only the one word before.
Data filtering drops low-quality, unsafe or off-target text from a corpus before training, using rules and classifiers.
In data parallelism every GPU holds a full copy of the model and trains on a different slice of each batch, then gradients are averaged.
Decoding strategies (greedy, beam search, temperature, top-k, top-p, speculative decoding) are the rules that turn a model's next-token probabilities into an actual text.
Deduplication removes repeated or near-repeated documents from training data so the model does not memorise them or over-weight them.
Domain specialization adapts a general language model to one field, such as law or medicine, by continued training or fine-tuning on that field's text.
The embedding dimension is the number of values in each embedding vector; larger dimensions capture more nuance but require more compute and memory.
An embedding lookup table is a matrix with one row per token; the model fetches a token's row to get its vector.
Entity embeddings give each item, such as a user or product ID, a learned vector so a model can use categories as numbers.
Evaluation methodology is how a test is built and run: the data, the metric, the repeats and the checks that keep the score honest.
FastText builds a word vector from the word's character pieces, so it can give a vector to a word it never saw whole.
In a transformer, the feed-forward network (FFN) is a two-layer MLP applied independently to each position after attention, adding nonlinear capacity.
GPT is a transformer decoder pretrained with causal language modeling that generates text autoregressively, one token at a time.
Incremental decoding keeps the keys and values of tokens already processed, so each new token computes only its own query, key and value, adds the key and value to the cache, and attends over the cache. The result must equal full recomputation.
InfoNCE is a softmax-based contrastive loss that treats one positive against many negatives, maximizing mutual information between paired views.
A jailbreak is an input crafted to make a model ignore its safety training and produce something it would normally refuse.
Knowledge editing changes a specific fact stored in a trained model without retraining it from scratch.
A large language model gives a chance to each possible next piece of text, learned from a very large amount of text by adjusting a very large number of dials called parameters.
LLM evaluation measures a model with benchmarks (MMLU, HumanEval), human preference arenas and your own held-out tests; every benchmark saturates or leaks eventually, so use several and check variance.
The logit lens reads an intermediate layer's output as if it were the final layer, to see what the model is leaning toward so far.
In a chatbot each word may attend only to itself and earlier words, because later words have not been written yet; experts call this the causal mask.
LoRA (Low-Rank Adaptation) fine-tunes large language models by decomposing weight updates into two small low-rank matrices, training only 0.1-1% of parameters while matching full fine-tuning performance.
Masked language modeling randomly hides tokens in the input and trains the model to predict them from surrounding context.
Mechanistic interpretability tries to reverse-engineer what a trained network computes by studying its residual stream, attention heads, features and circuits, rather than only its inputs and outputs.
MEMIT extends the ROME idea to write many facts at once across several layers.
Model collapse is the loss of variety and quality when models are trained again and again on the output of earlier models.
Multi-head attention runs several attention operations in parallel, each learning to focus on different types of relationships.
Nucleus (top-p) sampling restricts token selection to the smallest set of tokens whose cumulative probability exceeds a threshold p, balancing diversity and coherence.
Pipeline parallelism places different layers on different GPUs and passes micro-batches through them like an assembly line.
Positional encoding adds information about token order to the input embeddings since attention itself has no notion of sequence position.
Pretraining data is the large text collection a model first learns from; its sources and quality shape what the model can do.
A process reward model scores each intermediate reasoning step rather than only the final answer, enabling finer-grained training signal for reasoning.
Prompt engineering crafts input text to steer a language model's output through techniques like zero-shot, few-shot, and chain-of-thought prompting.
PPO constrains policy updates to a trust region using a clipped objective, balancing learning speed with training stability.
QLoRA combines 4-bit quantization of the frozen base model with LoRA adapters in fp16, enabling fine-tuning of 7B+ models on a single consumer GPU.
Reasoning models are LLMs trained to perform extended chain-of-thought reasoning before producing a final answer, improving performance on complex tasks.
Red-teaming is deliberately attacking a system to find failures and unsafe behaviour before real users do.
A reward model is trained on human preference pairs to score outputs, providing the scalar signal that policy optimization (PPO, DPO) maximizes during RLHF.
RLHF learns a reward model from human preference comparisons and optimises the model against it; DPO reaches the same goal directly from preference pairs.
ROME edits one fact by changing the weights of a single layer found to store it.
Scaling laws are empirical fits showing that a language model's loss falls smoothly as a power law in parameters, data and compute, which lets labs choose a compute-optimal balance before training.
Self-Instruct has a model write its own instruction and answer pairs from a few seed examples, then trains on them.
The supervised fine-tuning pipeline takes instruction-response pairs through dataset preparation, tokenization, LoRA training, and evaluation to customize a pretrained LLM for a specific task.
A sparse autoencoder rewrites a model's internal activations as a larger set of features of which only a few are active at a time, which are easier to read.
Speculative decoding uses a small draft model to propose multiple tokens that a larger model verifies in parallel, speeding up inference 2-3x.
Structured generation makes a model return data in a fixed shape, such as a valid JSON object, instead of free text.
Synthetic data is training text produced by a model rather than collected from people, used to fill gaps or teach specific skills.
Tensor parallelism splits the matrices inside a single layer across GPUs so each device computes part of every layer.
Test-time compute scales inference by allowing a model to spend more computation (e.g., longer reasoning chains) on harder problems.
A token is a small piece of text, often a word or part of a word, that a chatbot reads and writes one at a time.
A token embedding maps each discrete token ID to a dense, learnable vector that captures its semantic meaning in context.
Tokenization splits raw text into tokens (subwords, words, or characters) that a model can process as numerical input.
Tool calling lets a model output a structured request to run a function, which the application executes and returns to the model.
The transformer architecture uses stacked self-attention and feed-forward layers with residual connections to process sequences in parallel.
Most broken transformer code goes wrong in four places: the wrong axis or a reshape that mixes tokens, operations in the wrong order (a mask applied after the softmax, a norm on the skip path), a score that overflows, and a fast path that is not equal to the simple one.
A vision encoder (typically a Vision Transformer like ViT or SigLIP) converts an image into a sequence of feature vectors that can be projected into a language model's embedding space.
A VLM combines a visual encoder, projection layer, and language model to process images alongside text, enabling multimodal understanding and generation.
A Vision Transformer (ViT) splits an image into fixed-size patches, linearly embeds them, and processes the sequence with a standard transformer encoder for image classification.
A vision-language model reads images and text together, so it can describe a picture, answer questions about it, or embed it in a space shared with text.
Visual instruction tuning fine-tunes a VLM on image-text instruction-response pairs, teaching it to follow instructions that require visual understanding.
A vocabulary is the complete set of unique tokens a model can recognize; out-of-vocabulary words must be broken into known subword tokens.
Word embeddings map words to dense vectors in a continuous space where semantically similar words are close together, enabling neural networks to process language.
Word2Vec learns word embeddings by training a shallow neural network to predict context words (Skip-gram) or a target word from context (CBOW).
ZeRO and FSDP shard optimizer state, gradients and parameters across GPUs so each device stores only a fraction of the training memory.
Zero-shot classification predicts classes the model never saw in training by comparing inputs against text descriptions of candidate labels.
3D Gaussian splatting stores a scene as many coloured 3D Gaussians and draws them by projecting them to the screen, which renders much faster than a NeRF.
Adaptive layer norm lets a small network read the noise level and class label and set the scale and shift of every normalisation layer, which is how a diffusion transformer is told what time it is.
AI watermarking embeds imperceptible markers in generated content (images, text, audio) to enable later detection and attribution of AI-generated media.
Audio generative models make speech, music and sound by predicting codec tokens one after another or by running diffusion on a spectrogram or audio latent.
An autoencoder compresses input data into a low-dimensional bottleneck (encoding) and then reconstructs it, learning efficient representations.
A generator copies the patterns in its examples, including unfair or missing ones, so skewed data gives skewed output.
C2PA attaches signed provenance data to a file that records how it was made and edited; it can be stripped, so it proves origin only when it is present and intact.
Classifier-free guidance steers generation toward a prompt by extrapolating from the unconditional prediction toward the conditional one: eps_u + s * (eps_c - eps_u). At s = 1 you get the plain conditional model; larger s follows the prompt harder and varies less.
CLIP Score measures text-image alignment by computing cosine similarity between CLIP text and image embeddings; higher scores mean the generated image better matches the prompt.
A consistency model learns to map any point on a diffusion trajectory straight to the clean sample, which allows generation in one to four steps.
Controllable generation steers a diffusion model with extra signals beyond the text prompt, such as pose maps, reference images, small trained adapters, masks and edit instructions.
ControlNet adds a spatial condition such as a pose or edge map to a frozen diffusion model through a trainable copy of its encoder joined by zero-initialised layers.
Cross-attention lets each position in one sequence, such as a patch of the picture, look up and mix in information from another sequence, such as the prompt tokens.
DDIM reuses a trained diffusion network but samples along a deterministic path that can skip steps, so good images often need 20 to 50 steps instead of 1000.
DDPM is the denoising diffusion model that adds Gaussian noise over many small steps and trains a network to predict the noise with a simple mean squared error loss.
DDPO treats the denoising chain as a decision process and uses a policy-gradient method to raise a reward model's score for the final image.
Denoising is the process of training a neural network to predict and remove noise from corrupted data, which is the core mechanism of diffusion models.
Denoising score matching trains a network to point from a noisy sample back toward the clean one, and for Gaussian noise the target is minus the noise divided by its size.
Different diffusion papers run time in different directions, scale the noisy picture differently and ask the network for different outputs, but one signal-to-noise ratio lines them all up.
Diffusion distillation trains a fast student to reproduce in a few steps what a slow diffusion teacher produces in many.
Diffusion models generate data by learning to reverse a gradual noise-addition process, iteratively denoising random noise into coherent samples.
A diffusion transformer replaces the U-Net denoiser with a transformer that works on patches of the latent and is told the noise level through its normalisation layers.
Diffusion-DPO fine-tunes an image diffusion model directly on pairs of preferred and rejected images, with no separate reward model and no reinforcement learning loop.
A picture can be melted into static a little at a time by a fixed rule. A model learns to guess the static, and making a new picture means starting from pure static and cleaning it up step by step.
Discrete diffusion corrupts a sequence of codes by deleting pieces instead of adding blur, and learns to put them back.
The discriminator in a GAN is a classifier that learns to distinguish real data from the fake data produced by the generator.
DPM-Solver treats sampling as numerical integration, solving the linear part of the ODE exactly and approximating only the network part, so about 10 to 20 network calls can be enough.
EDM is a design framework that leaves the data unscaled, names the noise level sigma directly and treats the noise levels, loss weights, network scaling and sampler as separate choices.
The ELBO is a lower bound on the log-likelihood of the data; training a VAE or a diffusion model maximises it, which balances reconstruction quality against how close the latent distribution stays to the prior.
Flow matching learns a vector field that transports a simple distribution (noise) to a complex one (data) along straight paths, enabling fast generation.
The Fréchet distance compares two bell-curve fits (a mean and a covariance each) with one number; FID is this distance computed on image features, and it is also the base of FVD for video.
FID measures the distance between the feature distributions of real and generated images using an Inception network; lower FID means more realistic and diverse outputs.
FVD applies the Fréchet distance to features from a video network (I3D in the original work), so it scores both the look of frames and how motion unfolds over time.
A GAN pits a generator (creates fake data) against a discriminator (detects fakes) in a game that drives both to improve.
A generative program makes new things (text, pictures, sound, video, 3D shapes) instead of sorting existing ones, and the four main ways of doing it share one idea: learn what real examples look like, then draw new ones.
Generative AI ethics covers deepfakes, copyright of training data, consent, bias amplification, and environmental cost — the responsibilities that come with creating synthetic content.
Most broken diffusion and flow code goes wrong in three places: a flipped sign, a flipped time direction, and alpha used where alpha bar was meant.
Generative models learn the underlying distribution of training data so they can create new, similar samples rather than just classify existing ones.
The generator in a GAN takes random noise as input and produces synthetic data samples that attempt to fool the discriminator.
The guidance dial sets how hard the clean-up is pushed toward your prompt: low values give varied pictures that may ignore the words, high values follow the words closely but look samey or overdone.
Hallucination is when an LLM generates plausible-sounding but factually incorrect or unsupported information, a key problem that RAG helps mitigate.
Inception Score evaluates generative model outputs by measuring image quality (confident classification) and diversity (spread across classes) using a pretrained Inception network.
The information bottleneck forces a model to compress inputs into a lower-dimensional representation, retaining only the most relevant information for the task.
IP-Adapter feeds a reference image to a diffusion model through an extra cross-attention branch that sits beside the text branch, so no per-image training is needed.
KID compares real and generated image features with a kernel two-sample statistic; unlike FID its estimate is unbiased, so it behaves better on small sample sizes.
KL divergence loss in VAEs penalizes the encoder's learned distribution for diverging from a standard normal prior, ensuring a smooth, usable latent space.
Langevin dynamics draws samples by repeatedly stepping along the score (the gradient of the log density) and adding a small amount of Gaussian noise.
A latent consistency model distils a latent diffusion model so it can produce a good picture in about four steps instead of dozens.
Latent diffusion applies the diffusion process in a compressed latent space rather than pixel space, dramatically reducing compute while preserving quality.
Latent space is the compressed, abstract representation space where each point corresponds to a possible data sample.
Masked generation starts with every cell hidden and repeatedly fills in the cells the model is surest about, so many codes are written per pass.
A model can sometimes reproduce a training example almost word for word or pixel for pixel, which is why private data should never be fed to a tool you do not control.
A multimodal diffusion transformer gives text tokens and picture tokens their own weights but lets them attend to one another in a single joint attention step.
Mode collapse occurs when a GAN's generator learns to produce only a limited variety of outputs, failing to represent the full diversity of the training data.
Multimodal generation produces outputs across different modalities (image, video, audio, 3D) from a single model conditioned on text or other inputs.
A neural radiance field is a small network that maps a 3D position and viewing direction to colour and density, and it is trained by rendering images and comparing them with photos.
A neural audio codec compresses sound into a few discrete tokens per second with an encoder and residual vector quantisation, and a decoder turns the tokens back into a waveform.
Next-scale prediction writes a picture coarse to fine, predicting a whole grid of codes at each scale instead of one code at a time.
A chatbot's one job at every step is to give a chance to each possible next piece of text, pick one at random by those chances, and repeat until the reply is done.
In diffusion models, the neural network learns to predict the noise that was added to a clean sample, enabling step-by-step denoising during generation.
A noise schedule defines how much noise is added at each step of the forward diffusion process, controlling the difficulty of the denoising task.
A normalizing flow is a chain of invertible layers that turns simple noise into data, which gives an exact likelihood through the change-of-variables formula.
An ODE sampler walks from noise to a picture along the probability-flow ODE with no fresh noise, and Euler, Heun and DDIM with eta 0 are different ways of taking its steps.
Patchifying cuts a latent grid into small square patches and turns each patch into one token, so a transformer can read the picture the way it reads a sentence.
Preference tuning adjusts a trained image model with human or reward-model judgements of which outputs are better, so it follows prompts and tastes that the plain noise-prediction loss does not capture.
Reconstruction loss measures how well a decoded output matches the original input, serving as the primary training signal for autoencoders.
Rectified flow trains a network to predict the velocity along a straight line from noise to data, which allows sampling in few steps.
The reparameterization trick writes a random latent as z = mu + sigma * eps with eps drawn from N(0, I), so gradients can flow through the sampling step into mu and sigma.
Sampling means reaching into a bag of examples the model has learned and pulling one out at random. Chance is why the same model gives a new result each time instead of a copy.
Score distillation sampling uses a frozen 2D diffusion model as a critic: it renders the 3D scene, adds noise, and pushes the 3D parameters in the direction the denoiser says would make the render look more like the prompt.
Score matching trains a model to estimate the gradient of the data distribution's log-probability, guiding the reverse diffusion process.
Score-based models learn the score of the data at many noise levels and sample by following it from noise to data; this is the same idea as noise-prediction diffusion models.
Temperature scaling adjusts the sharpness of the probability distribution over next tokens, with lower values producing more deterministic output.
A text encoder turns a prompt into a list of number lists, one per token, that a picture model can read; CLIP and T5 are the common choices.
Text-to-image generation creates images from natural language descriptions by conditioning a generative model on text embeddings.
V-prediction trains the network to output a velocity that mixes the noise and the clean picture, which stays well behaved at both high and low noise.
A VAE maps inputs to a probability distribution in latent space rather than a fixed point, enabling smooth interpolation and generation of new samples.
Video diffusion denoises a stack of frames together in a compressed spacetime latent, so motion stays consistent from frame to frame.
Video generation extends image diffusion with a time axis, using spacetime patches, temporal attention and a video autoencoder to keep frames consistent.
A VQ-VAE snaps each encoder output to the nearest vector in a learned codebook, giving a grid of discrete codes that a sequence model can predict like text tokens.
A watermark hides a signal in an image or audio clip, or in the model that makes it, so that a detector can later tell whether the content came from a particular generator.
RL + RAG + AI Agents
A2C is the synchronous actor-critic algorithm where multiple parallel workers compute advantages and update a shared policy in lockstep batches.
A3C runs many actor-learners asynchronously on CPU threads, each updating shared parameters with its own gradients — no replay buffer needed.
Actor-critic methods use two networks: an actor that selects actions and a critic that estimates value, combining policy gradient with value-based learning.
MCTS guided by a policy network and a value network, first trained on human games and then improved by self-play.
Self-play with MCTS and a single network, trained tabula rasa with no human data.
Value mean-squared error plus cross-entropy to the MCTS visit distribution plus L2 regularization.
Subtract a state-dependent value from the return in a policy gradient to cut variance without adding bias.
Treat expert demonstrations as a supervised dataset of state-action pairs and fit a policy to them.
The Bellman equation expresses the value of a state as the immediate reward plus the discounted value of the next state, enabling recursive value computation.
The value of a state equals the immediate reward plus the discounted value of what follows; it turns a long-horizon problem into one-step updates.
Add a penalty that pushes down Q-values on actions not supported by the dataset.
Continuous control RL outputs real-valued actions (torques, velocities) instead of discrete choices — required for robotics, driving, and physics simulation.
Minimize regret at every information set to approach a Nash equilibrium in imperfect-information games.
Run the learner, have the expert label the states the learner visits, and retrain on the aggregate to fix covariate shift.
Cast RL as sequence modeling: predict the next action given past states, actions and the return-to-go.
A DQN replaces the Q-table with a neural network to handle high-dimensional state spaces like raw pixel inputs.
DPO fine-tunes language models directly from preference pairs without needing a separate reward model, simplifying the RLHF pipeline.
The discount factor (gamma) controls how much an RL agent values future rewards versus immediate ones; gamma near 1 means far-sighted, near 0 means myopic.
Select the next action with the online network and evaluate it with the target network to reduce overestimation.
Learn a latent world model from pixels and train the policy entirely on imagined rollouts inside it.
Split the Q-network into a state-value stream and an advantage stream, then recombine them.
Interleave real experience with simulated experience from a learned model to speed up learning.
A decaying memory of recently visited states that lets one TD error update many states at once.
Epsilon-greedy picks the best known action most of the time but takes a random action with probability epsilon to ensure exploration.
Experience replay stores past transitions in a buffer and samples random mini-batches for training, breaking temporal correlations and improving stability.
The exploration-exploitation dilemma balances trying new actions to discover better rewards versus repeating known good actions.
Generative adversarial imitation learning: a discriminator tells expert from learner behavior and supplies the reward.
An exponentially weighted sum of TD errors that trades bias against variance in the advantage estimate.
Any interleaving of policy evaluation and policy improvement; almost every RL algorithm is an instance.
A plan read off a Q-table by taking the biggest number in each state's row. Alone it can freeze on the first route that worked, so learners mix in a small share of random moves.
Group Relative Policy Optimization: score each sampled response against its group's mean reward, with no critic.
Decompose a long-horizon task into reusable sub-behaviors chosen by a higher-level policy.
IMPALA scales actor-critic to thousands of distributed actors using V-trace off-policy correction, decoupling acting from learning for high throughput.
Learn values with expectile regression so the Bellman backup never evaluates out-of-distribution actions.
Give the agent a self-generated reward, such as curiosity or novelty, to drive exploration when external reward is sparse.
Infer the reward function that makes the expert's behavior look optimal.
Multi-agent actor-critic with a centralized critic that sees all agents and decentralized actors.
An MDP formalizes sequential decision-making with states, actions, transition probabilities, and rewards, assuming the Markov property.
Max-entropy RL augments the reward with a policy entropy bonus, encouraging the agent to act as randomly as possible while still solving the task.
Model-based RL learns an internal model of the environment's dynamics, enabling the agent to plan ahead by simulating future states.
Estimate values by averaging the returns of complete episodes, with no model of the environment.
MCTS builds a search tree by simulating random rollouts from each state, balancing exploration and exploitation to find the best action.
Several learners share an environment, so each one faces a non-stationary world.
A game with several levers, a hidden payout chance for each, and no changing state; the aim is to collect many wins by balancing trying new levers against repeating the best one so far.
AlphaZero's recipe with a learned latent model in place of the simulator.
Unroll the learned dynamics K steps and train value, policy and reward predictions at every step.
Learn about one policy (usually the greedy one) while following another that explores.
Learn a policy from a fixed dataset of logged transitions with no further interaction.
Learn options end to end with intra-option policy gradients and a termination gradient.
Temporally extended actions defined by an initiation set, an intra-option policy and a termination function.
A policy maps states to actions (or action probabilities) and defines the agent's behavior strategy.
Policy gradient methods directly optimize the policy by computing gradients of expected reward with respect to policy parameters.
Alternate between evaluating the current policy and greedily improving it until the policy stops changing.
Clip the probability ratio so the objective goes flat once the policy moves beyond 1 plus or minus epsilon.
Sample replay transitions in proportion to their TD error so surprising experiences are replayed more often.
The AlphaZero selection rule: UCB with the policy network's prior probability scaling the exploration bonus.
Q-learning learns a table of state-action values (Q-values) through trial and error, converging to the optimal policy without needing a model of the environment.
A table with one number for every (state, action) pair: the agent's guess of how good that move is, counting the future. It starts at zero and is filled in by small updates.
Factor a team Q-value into per-agent Q-values through a monotonic mixing network.
A single agent that combines Double, Dueling, prioritized replay, multi-step returns, distributional RL and noisy nets.
The basic policy-gradient algorithm: raise the log-probability of actions in proportion to the return that followed.
A reward is one number handed back after an action: positive is good, negative is bad. It is a score and not an instruction, it is often delayed, and the agent chases it exactly as written.
A reward model is a neural network trained on human preference comparisons to predict which of two outputs a human would prefer, enabling RLHF.
The reward signal is a scalar feedback value that tells an RL agent how good its last action was, guiding it to learn which behaviors to repeat.
Train reasoning models with RL where the reward is an automatic check, such as a math answer or a passing unit test.
RLHF (Reinforcement Learning from Human Feedback) fine-tunes language models using a reward model trained on human preference comparisons.
SAC maximizes both reward AND policy entropy, giving continuous-control RL stable exploration without separate epsilon-greedy or noise schedules.
On-policy TD control: update Q toward the reward plus the Q-value of the action the agent actually takes next.
Train an agent against copies of itself so the opponent improves as the agent does.
An MDP whose actions last a random number of steps, giving a Bellman equation discounted by gamma to the tau.
In RL, an agent observes a state, takes an action, and receives a reward that signals how good the action was.
Blend n-step returns with a decay lambda, interpolating between one-step TD and Monte Carlo.
TD3 fixes DDPG's overestimation bias with twin Q-networks, delayed policy updates, and target policy smoothing — a robust deterministic continuous-control baseline.
Update a value estimate toward the reward plus the discounted estimate of the next state, one step at a time.
New Q = old Q + alpha x (target - old Q), where target = reward + gamma x the best Q in the state landed on. Alpha sets how far to move; gamma sets how much the future counts.
An agent sees a state, picks an action, and the environment answers with a reward and a new state; the cycle repeats and the agent learns from the scores.
Sample a plausible value for each arm from its posterior and play the arm with the highest sample.
Constrain each policy update to a KL-divergence trust region so improvement is monotonic in theory.
Pick the arm whose estimated value plus an uncertainty bonus is highest, so under-explored arms get tried.
A value function estimates the expected cumulative reward from a given state (or state-action pair) under a particular policy.
Repeatedly apply the Bellman optimality backup to every state until the values stop changing, then read off the greedy policy.
A learned model of how the environment changes in response to actions, used for planning or imagined rollouts.
Agentic RAG adds intelligent decision points to retrieval pipelines, allowing the system to route queries, evaluate relevance, and retry with different strategies when retrieval fails.
ANN algorithms (HNSW, IVF, LSH) trade a small amount of accuracy for massive speed gains, enabling billion-scale vector search in milliseconds.
BM25 scores a document for a query by counting the query terms it contains, weighting rare terms more and damping long documents. It is the standard keyword (sparse) ranking function.
Chunk overlap ensures that context at chunk boundaries is not lost by including shared text between adjacent chunks, improving retrieval quality.
Chunking splits large documents into smaller pieces that fit within embedding model and LLM context windows while preserving meaning.
ColBERT keeps one embedding per token and scores a document by summing, for each query token, its best match among the document tokens (MaxSim). It sits between a bi-encoder and a cross-encoder.
ColPali embeds a page image as many patch vectors with a vision-language model and retrieves with ColBERT-style late interaction, so layout, tables and figures count as evidence.
Cosine distance (1 minus cosine similarity) measures how different two vectors' directions are; it is the primary distance metric for embedding-based retrieval.
A cross-encoder reads the query and one document together and outputs a relevance score. It is more accurate than comparing two separate vectors but too slow to run over a whole corpus.
An embedding model converts text, images, or other data into dense vectors; popular choices include OpenAI text-embedding-3, Cohere Embed, and open-source models like BGE and E5.
Embeddings are dense vector representations that capture semantic meaning, placing similar items close together in continuous space.
Faithfulness is the fraction of the claims in a generated answer that the retrieved context supports. A high score means grounded, not necessarily correct.
GraphRAG extracts entities and relationships from a corpus into a knowledge graph, groups them into communities, and summarizes each community so corpus-wide questions can be answered.
A grounded prompt carries numbered notes, a rule to answer only from them and cite the number, and a way out such as 'I could not find that' for when the notes are silent.
Grounding connects an LLM's responses to verifiable external sources, ensuring outputs are factual and traceable rather than purely generated.
Hit at k is the share of questions whose right note is in the top k. Recall at k is the share of the right notes that came back, which differs from hit rate only when a question needs several notes.
HNSW stacks sparse graph layers over a navigable small-world graph so a search starts with long jumps and ends with local steps. It answers in milliseconds and keeps the whole graph in memory.
Hybrid retrieval runs a keyword ranker and a dense vector ranker and merges the two lists, so exact identifiers and paraphrases are both found.
Hybrid search combines keyword-based (BM25) and semantic (vector) search to leverage the strengths of both exact matching and meaning-based retrieval.
HyDE asks a model to write a hypothetical answer first, then searches with that answer's embedding instead of the short question, which often lands closer to real documents.
IVF-PQ clusters vectors into cells and searches only the nearest few, and compresses each vector into short product-quantization codes. It trades some recall for a large cut in memory.
A knowledge graph stores information as entities and relationships (triples), enabling structured reasoning and multi-hop queries.
In several studies, language models used facts at the start and end of a long context better than facts in the middle, so accuracy against position looks like a U.
MMR picks results one at a time, trading relevance to the query against similarity to the results already chosen, so the final list is relevant and not repetitive.
Reciprocal rank is 1 divided by the rank of the first right result, so rank 1 gives 1, rank 2 gives 0.5 and rank 10 gives 0.1. MRR is the average over your questions.
NDCG scores a ranked list by giving each relevant result a gain that is discounted by its rank, then dividing by the best possible score, so putting relevant results first earns more.
Prompt injection hides instructions in text the model reads, such as a retrieved document, so the model may follow the attacker instead of the developer. Treat retrieved text as untrusted.
Query rewriting turns the user's words into queries that retrieve better: expanding, splitting into sub-questions, or stepping back to a more general question.
Query routing classifies a user's intent and directs the query to the most appropriate retrieval source or strategy, such as vector search, web search, SQL, or no retrieval.
RAG has three steps: find the best notes, paste them into the prompt with numbers, and answer from them. You can build a working version with plain Python and ten notes.
Retrieval-Augmented Generation grounds LLM responses in external knowledge by retrieving relevant documents before generating an answer.
RAG evaluation measures retrieval relevance, answer faithfulness, and end-to-end quality to ensure the system returns accurate, grounded responses.
RAG monitoring tracks retrieval hit rates, latency, cost, and answer quality in production to detect regressions and maintain reliability.
A RAG pipeline retrieves relevant documents from a knowledge base and includes them as context when generating an LLM response.
RAGAS is a set of reference-free RAG metrics computed with an LLM judge: faithfulness, answer relevancy, context precision and context recall.
Reciprocal rank fusion merges several ranked lists by giving each document the sum of 1 over (k + its rank) across the lists, with k usually 60. It needs no score calibration.
Reranking uses a cross-encoder or other model to re-score and reorder retrieved documents for higher relevance before generation.
Retrieval selects the most relevant documents or passages from a knowledge base based on a user query, typically using vector similarity.
An answer key pairs real-sounding questions with the notes that should come back. You write it by reading the notes, before running any search, and re-run it after every change.
Retrieval-augmented means grounding a generative model's output in external knowledge fetched at query time, reducing hallucination and enabling up-to-date responses.
Self-RAG trains the model to decide whether to retrieve, evaluate retrieved document relevance, and verify that its response is supported by evidence, using special reflection tokens.
A semantic cache stores answers keyed by query embeddings and returns a stored answer when a new query is similar enough, which skips the model call.
Semantic similarity measures how close in meaning two texts are, typically computed as cosine similarity between their embedding vectors.
A vector database stores and indexes embedding vectors for fast approximate nearest-neighbor search at scale.
Vector similarity measures how close two embeddings are, typically using cosine similarity or dot product, to find semantically related content.
Word overlap search scores a note by counting the words it shares with the question. Filler words mislead it and ties are luck, so dropping filler words and weighting rare words helps, but it still misses a question worded differently from the note.
Agent architecture defines the structural design of an AI agent system including the LLM backbone, tool registry, memory modules, and orchestration logic.
Agent benchmarks are standardized test suites that measure an AI agent's ability to complete tasks, use tools, and reason across diverse scenarios.
The capstone wires tools, ReAct, memory, an evaluator loop, cost caps, tracing, and CI evals into one agent you could ship.
Agent evaluation scores outcome, trajectory (steps and cost), and safety, using statistical assertions because runs vary.
Agent frameworks (LangChain, CrewAI, AutoGen, Anthropic Agent SDK) provide pre-built components for tool registries, memory, orchestration, and multi-agent coordination.
The agent loop is the observe-think-act cycle where an AI agent perceives its environment, reasons about the next step, and executes an action.
Agent memory systems store short-term context and long-term knowledge so agents can maintain state across interactions.
Agent observability captures every prompt, tool call, retry, and token cost into traces so you can debug nondeterministic loops and attribute failures to a specific step.
Agent safety layers input guards, tool sandboxing, cost limits, loop detection, and human approval so one bad decision cannot become an incident.
In a workflow the builder fixes the steps in advance; in an agent the model chooses the next step while it runs. Ask who chooses the next step.
Prompt chaining, routing, parallelization, orchestrator-workers, and evaluator-optimizer: fixed-structure patterns to use before an autonomous loop.
An AI agent works towards a goal by choosing actions, using tools, and reading the results in a loop, instead of answering once and stopping.
AutoGen is a conversation-driven multi-agent framework with strong code execution.
Autonomous coding agents take a task description and independently explore codebases, plan changes, write code, run tests, and iterate until the task is complete.
Browser agents automate web interactions using tools like Playwright or Puppeteer, combining LLM reasoning with programmatic DOM manipulation.
Code agents autonomously read codebases, plan changes, edit files, run tests, and iterate on failures to produce working software changes.
Computer use enables AI agents to interact with software through screenshots and mouse/keyboard actions, automating any GUI-based application without APIs.
Constrained decoding enforces output grammar (JSON schema, regex, BNF) at the token-sampling level — function-calling accuracy jumps from ~90% to 100% with it.
CrewAI is a multi-agent framework where role-based agents with distinct personas collaborate through task delegation and crew orchestration.
Distributed tracing stitches spans from many services into a single causal timeline using trace and span IDs, exposing latency and failure across the whole agent stack.
One call generates, another evaluates against a criterion, and the loop repeats until the output passes.
Function calling is a structured protocol where an LLM outputs a JSON schema specifying which function to call with what arguments.
Function calling works by injecting tool schemas into the prompt, then constraining the model to emit a structured JSON call that the runtime parses and dispatches.
Guardrails are safety mechanisms (input/output filters, cost limits, human-in-the-loop) that constrain agent behavior to safe and intended actions.
GUI agents perceive screens as images, reason about visual layouts, and take physical actions (clicks, keystrokes) to interact with graphical user interfaces.
Human-in-the-loop systems require human approval at critical decision points, keeping AI agents safe by preventing irreversible actions without oversight.
LangChain is an agent framework providing composable chains, tool integrations, memory modules, and LangGraph for stateful graph-based orchestration.
LangGraph models an agent as a typed state graph with nodes, edges, checkpoints, and human-in-the-loop steps.
LATS combines tree search with reflection so an agent can explore, score, and backtrack across many action sequences.
Another name for MCP: the shared protocol between agent hosts and tool servers.
MCP is an open protocol that lets any agent host discover and call tools, resources, and prompts from a server written once.
Multi-agent systems coordinate multiple specialized AI agents that collaborate, delegate, and communicate to solve complex tasks.
OpenTelemetry is a vendor-neutral tracing spec: traces span across LLM calls, tool calls, and DB queries, making agent debugging tractable.
An orchestrator plans subtasks at runtime and dispatches them to worker calls, then integrates the results.
Parallel tool calls let the model emit multiple independent tool invocations in one turn so the runtime can fan them out concurrently, cutting latency dramatically.
Planning is the ability of an agent to decompose a complex goal into a sequence of sub-tasks and execute them in the right order.
A production agent is one that survives real traffic: hard cost caps, loop limits, safe tools, traces, and a regression eval set.
Production agents are traced span by span, budgeted, alerted on, and evaluated in CI before and after release.
ReAct interleaves a Thought, an Action, and an Observation on repeat, so each tool call is tied to what the agent has seen so far.
The ReAct pattern interleaves reasoning traces and actions, letting agents think step-by-step before each tool call.
Reflexion retries a task after writing a short natural-language lesson about why the last attempt failed, with no weight updates.
Alias used by registry prerequisites: the lesson on retrying with a written lesson and on self-refinement.
A scratchpad is a working memory buffer where an agent records intermediate reasoning steps, observations, and plans during multi-step task execution.
Self-critique asks a model to find faults in its own output and revise it, with or without an external pass/fail signal.
A step limit is a number that stops the agent loop after that many rounds, so a confused agent cannot run, and spend, for ever.
SWE-bench is the standard benchmark for code agents, testing whether they can resolve real GitHub issues by producing patches that make failing tests pass.
In code the agent loop asks a brain function for an action, calls a tool function, appends the result to a notebook list, and repeats until the brain finishes or the step limit is reached.
The three steps of the ReAct loop: reason about what to do, call a tool, read the result.
A tool schema is a structured JSON description of a function's name, parameters, and types that tells an LLM what tools are available and how to call them.
Tool use enables an LLM to invoke external functions (APIs, search, code execution) to take actions beyond text generation.
Trajectory evaluation assesses not just the final outcome but the sequence of steps an agent took, checking for efficiency, safety, and correctness.
Tree of Thought explores several reasoning branches and evaluates them before committing to one.
ML Engineering & Architecture
A/B testing compares two model variants on live traffic to measure which performs better on business metrics before full rollout.
Splitting live traffic between two models and comparing a business metric with a significance test before choosing one.
Input checks, robust training and monitoring that reduce the damage of adversarial or malicious inputs.
The roles, policies, reviews and records an organization uses to control how AI systems are built and used.
A workflow orchestrator that runs tasks as a DAG with scheduling, retries and dependency order.
A documented review of who a system affects, the risks, and the mitigations before it is deployed.
Amazon SageMaker is AWS's end-to-end ML platform providing managed training, endpoints, pipelines, and JumpStart for deploying foundation models.
Azure ML is Microsoft's ML platform with deep Microsoft ecosystem integration and exclusive access to Azure OpenAI Service for enterprise GPT-4 deployment.
Bias mitigation techniques (re-sampling, adversarial debiasing, threshold adjustment) reduce unfair disparities in model predictions across demographic groups.
CI/CD for ML automates model training, testing, validation, and deployment pipelines, ensuring reproducible and reliable model releases.
Packaging code, dependencies and runtime into an image so it runs the same way on any machine.
Updating a deployed model as new data arrives, with triggers and guards against forgetting and drift.
Cost architecture is the discipline of designing AI systems for economic viability through GPU selection, multi-model routing, token optimization, and caching strategies.
Cost optimization for ML means tuning batch size, cache hit rate, model size, and routing so spend tracks value — often a 10x lever once you measure cost-per-request.
Estimating how a new policy would have done from logged data of an old one, using importance weighting.
An agreed schema and quality promise between a data producer and its consumers, enforced by validation at the boundary.
Data drift occurs when the statistical distribution of production data changes from what the model was trained on, degrading performance.
Scheduled or streaming jobs that move, validate and transform data so training and serving read trustworthy inputs.
The standard file format and network protocol for medical images and their metadata.
A guarantee, set by a budget epsilon, that adding or removing one person's data barely changes the output.
Backups, failover and tested rollback so a service can be restored within an agreed time.
Training a small student model to imitate a larger teacher so it is cheaper to serve.
The common tool for building and running container images, including GPU-enabled ones for ML.
Training with per-example gradient clipping and added noise so the model satisfies differential privacy.
Data Version Control: Git-style versioning for large datasets and model files, stored in remote object storage.
The EU AI Act is a risk-tiered regulation (unacceptable, high, limited, minimal) that mandates documentation, human oversight, and conformity assessments for high-risk AI systems.
Recording the code, data, parameters and metrics of every run so any result can be compared and reproduced.
Fairness metrics (demographic parity, equalized odds, calibration) quantify whether a model's predictions are equitable across protected demographic groups.
A feature store is a centralized repository that manages, serves, and shares engineered features across ML models and teams, ensuring consistency between training and serving.
Training across many devices or sites by sharing model updates instead of raw data.
Measuring, attributing and budgeting the cost of GPUs, tokens and requests so AI features stay affordable.
Vertex AI is Google Cloud's unified ML platform offering custom training, prediction endpoints, TPU hardware, and BigQuery ML for SQL-based modeling.
GPU selection trades memory bandwidth, VRAM, FLOPs, and price (A100 vs H100 vs L4 vs consumer) — the right pick depends on model size, batch size, and latency budget.
Running several workloads on one GPU through partitioning or time slicing to avoid idle capacity.
The CT intensity scale, with water at 0 and air at about -1000, recovered from stored pixels by slope and intercept.
A runbook-first process to detect, bound, mitigate, communicate and then investigate a production failure.
Mixing two rankers' results in one list and counting which side the user clicks, for a more sensitive comparison than a split test.
A distributed log used to stream events between producers and consumers in near real time.
Knowledge distillation trains a small student model to mimic a large teacher model's outputs, transferring performance at a fraction of the compute cost.
An LLM gateway sits between your application and LLM providers, providing a unified API, load balancing, failover, rate limiting, cost tracking, and caching.
LLM routing sends each request to the cheapest model that can handle it — a small classifier or heuristic in front of a model cascade can cut spend 5-10x with no quality loss.
LLM system design layers retrieval, prompt assembly, model routing, guardrails, caching, and evals — the model is just one component in a much larger production stack.
LLMOps extends MLOps with prompt versioning, guardrails, LLM gateways, evaluation pipelines, and cost management specific to large language model workloads.
Working with CT, MRI and X-ray data, including pixel scaling, orientation and clinical metadata.
Multi-Instance GPU: splitting one supported NVIDIA GPU into isolated slices with their own memory.
The loop of data, training, deployment, monitoring and retraining that a production model lives in.
An ML pipeline automates the end-to-end workflow from data ingestion through feature engineering, training, evaluation, and deployment.
Pinning code, data, seeds and environment so a past training run can be repeated and give the same result.
ML security covers prompt injection, model theft, training-data poisoning, and inference-time exfiltration — threats that classical AppSec doesn't catch.
ML system design balances data pipelines, training infra, online/offline serving, monitoring, and rollback — interview-style frameworks force you to reason about all five together.
An open-source tool for tracking runs and registering model versions.
MLOps applies DevOps practices (CI/CD, versioning, monitoring) to machine learning systems for reliable, reproducible deployments.
A model card is a standardized document accompanying a trained model that details its intended use, performance metrics by demographic group, limitations, and ethical considerations.
Model compression reduces a model's size and compute requirements through techniques like quantization, pruning, and knowledge distillation.
Model drift is the degradation of a deployed model's performance over time as real-world data patterns shift away from the training distribution.
A model registry is a centralized catalog that versions, tracks, and manages trained model artifacts along with their metadata, metrics, and lineage.
Model serving deploys trained models behind APIs (REST, gRPC, streaming) to handle real-time or batch inference requests at scale.
Hosting many models on shared GPUs with routing, autoscaling and memory sharing to raise utilization.
A voluntary US framework that organizes AI risk work into Govern, Map, Measure and Manage.
Observability provides visibility into a deployed ML system's health through metrics, logs, traces, and drift detection.
The hospital system that stores and distributes medical images over DICOM networking.
Removing or transforming patient identifiers in images and metadata before data leaves the hospital.
PII handling means detecting, redacting, and avoiding logging personal data before it reaches prompts, embeddings, or training sets — a core requirement under GDPR, HIPAA, and CCPA.
Point-in-time joins reconstruct what a feature looked like AT a specific past moment — essential for training without future leakage from the feature store.
Methods that let you train and serve models while limiting what they reveal about individual records.
Integrating pipeline, serving, monitoring, governance and incident response into one hardened system.
Shortening prompts and context while keeping the information the model needs, to cut token cost and latency.
Prompt injection defense layers input sanitization, instruction hierarchies, output filters, and tool sandboxing — no single mitigation is sufficient, only defense in depth.
Prompt versioning tracks changes to system prompts like code — with version control, regression testing, and rollback — because prompt changes alter LLM behavior as much as code changes.
Pruning removes unnecessary weights or neurons from a trained model, reducing size and compute while preserving most of the original performance.
Quantization converts model weights from high-precision (32-bit float) to lower precision (8-bit int or 4-bit) to reduce memory and speed up inference.
Recommendation system design follows a candidate-generation then ranking funnel, with embeddings for recall and gradient-boosted or deep models for precision at the top.
A rule, run automatically in continuous integration, that blocks a new model unless every check passes and prints the reasons when it does not.
Fairness checks, documentation and governance practices that make an AI system accountable to the people it affects.
Step-by-step written procedures an on-call engineer follows during a known type of incident.
Threat models, PII handling and control frameworks applied to ML systems in production.
A model can get worse with no error and no code change because the world drifts. Teams log answers, match them to later labels, and alert when accuracy crosses a chosen line.
Three kinds of check on a candidate model: the data, the score on held-out cases against a floor and the current model, and behaviour on pairs with a known direction.
The six stops a prediction makes in a running service: request, input check, features, model, answer and log. The model is only one of them.
Training-serving skew is when features are computed differently in training vs serving (e.g., different timezones, units, or fallbacks) — a silent killer of model quality in production.
A server that hosts several models and frameworks behind one endpoint with batching and GPU scheduling.
An inference engine for language models that uses continuous batching and paged KV-cache memory.
A hosted service for logging experiments, comparing runs and running hyperparameter sweeps.