concept / machine-learning--hierarchical-clustering
Next task →
University/Machine Learning/Kernel and unsupervised/Hierarchical clustering
Algorithms · Kernel and unsupervised · Clustering and more

Hierarchical clustering

Hierarchical clustering in Algorithms → Kernel and unsupervised → Clustering and more. Modern ML is limited by memory movement and communication, not by arithmetic alone. Writing efficient kernels requires explicitly managing hierarchy, coalescing and parallelism.

39 template sectionsintermediate90 mingenerated template · not reviewed
Generated template — not a reviewed lesson. This page shares boilerplate with other generated pages, so its prose may not be specific to Hierarchical clustering. The structural heuristic reports 18/100, but that number is not an accuracy score and should not be read as one.Generated template: prose is not specific to this concept · Prerequisite chain incomplete · No interactive visualStudy a hand-authored reference lesson instead →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

Hierarchical clustering is a concept in Algorithms → Kernel and unsupervised → Clustering and more. Modern ML is limited by memory movement and communication, not by arithmetic alone. Writing efficient kernels requires explicitly managing hierarchy, coalescing and parallelism. The central question of this page is not what is it called but what problem forces it to exist, which assumptions make it valid, and how it fails. The compact statement is:

Roofline: t≥max⁡ ⁣(FLOPsFLOP/smax⁡,bytesBmax⁡),arithmetic intensity=FLOPsbytes.\text{Roofline: } t\ge\max\!\left(\frac{\text{FLOPs}}{\text{FLOP/s}_{\max}},\frac{\text{bytes}}{B_{\max}}\right),\qquad \text{arithmetic intensity}=\frac{\text{FLOPs}}{\text{bytes}} . For a GEMM of an M×K by K×N matrix, bytes ≈ 4(MK+KN+MN) and FLOPs ≈ 2MNK.

Everything below derives that statement, implements it, measures it and identifies the cases where it breaks.

2. Why this concept exists

Naive library calls hid the cost; CPU-style loops mapped badly to GPUs; early CUDA kernels achieved a fraction of peak bandwidth and had unstable occupancy.

Before Hierarchical clustering, practitioners either solved a restricted version by hand or accepted an unjustified heuristic. Hierarchical clustering appears because it buys a real guarantee — a bound, an invariance, a tighter approximation or a tractable computation — under assumptions you can state and test. In machine learning the pressure is usually scale: larger data, higher dimensions, longer contexts or larger models.

3. Historical background

CUDA (2006) made GPUs general-purpose; Tensor Cores (2017) and FlashAttention (2022) shifted the bottleneck from arithmetic to memory movement.

The idea did not appear fully formed. Earlier work supplied the notation and the motivating failure; later work supplied the derivation and the implementation. When reading the original literature, separate the theorem from the author's heuristic justification — the two are often presented together but have different status.

4. Fundamental problem

Modern ML is limited by memory movement and communication, not by arithmetic alone. Writing efficient kernels requires explicitly managing hierarchy, coalescing and parallelism.

Formally, the difficulty is that the object of interest is defined by a global property (an optimum, a distribution, an invariant, a limit) while we can only compute local quantities. Assumptions bridge that gap: Fixed hardware peak bandwidth and compute, sufficient occupancy, and a working set that fits the intended cache/shared-memory level. If any of them fails, the result may still be useful empirically, but the guarantee no longer applies.

5. First-principles explanation

Express the computation as many independent threads, arrange global-memory accesses so consecutive lanes read consecutive addresses, stage reused tiles in shared memory, and overlap communication with computation.

Derivation starts from the simplest possible model rather than from a definition. Count arithmetic and bytes moved. Compute arithmetic intensity and locate the roofline regime. Only after the local model is justified do we add the machinery specific to Hierarchical clustering.

6. Prerequisite concepts

You should be comfortable with: machine-learning--reproducing-kernel-hilbert-spaces. In particular, you must be able to manipulate the notation in section 8 and understand why each assumption in section 7 is needed. If a prerequisite is still listed as outlined in the curriculum, use the linked papers and the 11-step practical chain on its task page first.

7. Complete mathematical formulation

Roofline: t≥max⁡ ⁣(FLOPsFLOP/smax⁡,bytesBmax⁡),arithmetic intensity=FLOPsbytes.\text{Roofline: } t\ge\max\!\left(\frac{\text{FLOPs}}{\text{FLOP/s}_{\max}},\frac{\text{bytes}}{B_{\max}}\right),\qquad \text{arithmetic intensity}=\frac{\text{FLOPs}}{\text{bytes}} . For a GEMM of an M×K by K×N matrix, bytes ≈ 4(MK+KN+MN) and FLOPs ≈ 2MNK.

Assumptions. Fixed hardware peak bandwidth and compute, sufficient occupancy, and a working set that fits the intended cache/shared-memory level.

Domain of validity. The statement is made for the setting described above. Extending it to machine learning / Kernel and unsupervised requires new assumptions and a new proof; do not assume the formula transfers automatically.

8. Notation dictionary

| Symbol | Meaning | Type | |---|---|---| | xx | input / state / observation | vector | | θ\theta | parameters being learned or solved for | vector | | ff | objective, map or density under study | function | | ∇,∂\nabla,\partial | gradient / partial derivative | differential operator | | E\mathbb{E} | expectation under an implied distribution | operator | | ε,δ\varepsilon,\delta | tolerance and the radius it forces | positive scalar | | α,η,γ\alpha,\eta,\gamma | step size, learning rate, discount | scalar | | X\mathcal{X} | domain / feasible set | set | | TT | number of steps, samples or trials | integer |

Every symbol above is used with the same meaning throughout this page. The concept-specific symbols appear in section 7.

9. Step-by-step derivation

Steps

  1. Count arithmetic and bytes moved.
  2. Compute arithmetic intensity and locate the roofline regime.
  3. Tile the computation to reuse data in fast memory.
  4. Coalesce global loads across a warp.
  5. Measure with a profiler and compare to the roofline bound.

At each step, pause and check which assumption is doing the work. A step that seems obvious is usually hiding one: for Hierarchical clustering the hidden assumption is typically about regularity, independence or finite precision.

10. Proofs and proof intuition

Proof / proof intuition. The roofline bound follows because time cannot be less than either the arithmetic limit or the bandwidth limit; the max of the two lower bounds is therefore valid.

The standard proof is constructive: it exhibits the quantity that must shrink and shows it does. If you remove an assumption, locate the exact line of the proof that fails — that line is the boundary of the result.

11. Geometric interpretation

Threads form a 2D grid of tiles; each tile walks along the K dimension, loading panels of A and B into shared memory before computing an output tile.

Draw the objects before trusting the algebra. In two dimensions the statement usually reduces to angles, distances, projections or contour shapes; the same geometry survives in high dimensions even when you cannot plot it.

12. Visual explanation

Use the interactive visualizers in Practical Labs to see Hierarchical clustering change as its controlling parameters move. For this topic, plot the governing expression from section 7 against one variable at a time. Label axes with units, overlay the assumption boundary, and annotate the point where the conclusion stops holding. A visual that does not let you predict the outcome before changing a parameter is decorative, not explanatory.

13. Numerical worked example

Worked numerical example. For M=N=K=1024 fp32, FLOPs≈2.1e9 and bytes≈12.6MB. At 100 TFLOP/s the compute bound is 0.021ms; at 900GB/s the memory bound is 0.014ms — compute bound on this hypothetical device.

Redo this calculation by hand, then reproduce it in code. If your computed numbers disagree with the text, either the arithmetic or the implementation is wrong — find out which.

14. Real-world analogy

A warehouse with many workers: if everyone fetches from distant shelves separately, the conveyor belt is the bottleneck; stage a shared cart of parts first.

Analogies are scaffolding: they make the first step intuitive, but they break where the formal assumptions are stronger than the analogy. Always return to the equation after using one.

15. Algorithm pseudocode

algorithm TiledGEMM(A, B, tile):
    for tile_m, tile_n in grid:
        acc = zeros(tile)
        for k in range(0, K, tile):
            load A tile and B tile into shared memory
            acc += dot(A_tile, B_tile)
        write acc to C

The pseudocode intentionally omits engineering details. Add input validation, numerical guards and logging in the real implementation.

16. Implementation from scratch

import numpy as np

def roofline(flops, bytes_moved, peak_flops, peak_bw):
    return max(flops / peak_flops, bytes_moved / peak_bw)

def gemm_counts(m, k, n, dtype_bytes=4):
    return 2*m*k*n, dtype_bytes*(m*k + k*n + m*n)

f, b = gemm_counts(1024,1024,1024)
t = roofline(f, b, 100e12, 900e9)
assert t > 0 and f/b > 1
print(f, b, round(t*1e3,4), 'ms')

This implementation is deliberately small and dependency-light. Run it, then extend it to the concrete dataset named in the experimental section.

17. Professional library implementation

import torch
# Prefer fused library kernels before writing your own:
y = torch.nn.functional.scaled_dot_product_attention(q, k, v)
with torch.cuda.amp.autocast(dtype=torch.bfloat16):
    y = model(x)

The library version uses a battle-tested kernel. Compare it to your from-scratch version on a tiny input before trusting either on real data.

18. Code walkthrough

Scratch code. The function first validates its inputs, then performs the core computation and asserts a known answer. The assertion is the point: without a hand-computed reference, a wrong implementation looks identical to a right one.

Library code. The library call hides numerical safeguards (stable softmax, fused kernels, dtype handling). Know which safeguards it provides so you can reproduce them when writing your own Hierarchical clustering kernel.

19. Tensor and memory analysis

For a batch of shape (b,d)(b,d) in fp32, the input occupies 4bd4bd bytes and each same-sized buffer another 4bd4bd. A quantity of shape (b,n,n)(b,n,n) costs 4bn24bn^2 bytes, which becomes the dominant term once nn grows. Weights, gradients, optimizer state, activations and workspace; mixed precision halves the first two. On a GPU, also budget for allocator fragmentation, CUDA context and communication buffers; a theoretical fit is not the same as a successful allocation.

20. Time complexity

Measured in GB/s or TFLOP/s; kernel launch overhead (~5–10µs) dominates tiny tensors. Express the bound in terms of the problem dimensions you actually measured — sample count n, feature dimension d, sequence length L or vocabulary size V — and state whether it is per update or over the full training run. Report both asymptotic growth and measured wall-clock time, because constants and memory movement decide real performance.

21. Space complexity

Weights, gradients, optimizer state, activations and workspace; mixed precision halves the first two. Separate persistent state (parameters, buffers, caches) from transient working memory (activations, temporaries, communication buffers). The peak allocation, not the average, determines whether a job fits on the device. When you change batch size or precision, recompute this estimate rather than extrapolating from a small run.

22. Experimental demonstration

Sweep tile sizes and measure bandwidth; plot achieved GB/s against occupancy from Nsight Compute.

Pre-register the hypothesis, fix the seed before running, and keep a record of every failed attempt. Report at least three seeds so a reader can tell signal from noise.

23. Benchmark results

Compare naive, tiled and vendor kernels on the same GPU with warmup and 50 repetitions; report median and p95, not a single best run.

There is no legitimate universal benchmark number for this concept. Any claim of state of the art must name the dataset, hardware, precision, implementation and metric. Qualitative claims in this page are theory; numbers you obtain by running the experiment are evidence.

24. Limitations

  • Vendor libraries are often faster than hand-written kernels
  • Occupancy is not the same as performance
  • Portability across GPU generations is limited

Limitations are part of the result, not an appendix. A method whose assumptions you cannot check is a method whose conclusions you cannot trust when using Hierarchical clustering.

25. Failure scenarios

  • Uncoalesced accesses
  • Shared-memory bank conflicts
  • Race conditions from missing barriers
  • OOM from fragmentation

For each scenario, write down which assumption is violated, the earliest observable symptom and an automatic detector. A failure you cannot detect is a failure you will eventually ship.

26. Common misconceptions

  • More threads always faster
  • Tensor cores are useful for all dtypes

Misconceptions survive because the wrong story is often simpler than the correct one. Replace each with the precise statement from section 7.

27. Alternative approaches

  • Triton
  • cuBLAS/cuDNN
  • FlashAttention
  • CPU offload

Choose among alternatives by stating which assumption you are willing to drop and what you get in exchange. Compare them with the same budget and the same metric.

29. Research applications

  • Training acceleration
  • Inference serving
  • Custom operators
  • Distributed training

For each application, write one sentence about what Hierarchical clustering contributes and one about what it cannot contribute. Research uses a tool well when it knows its boundary.

30. Important research papers

  • A Theory of the Learnable — 1984, Communications of the ACM (library id: valiant1984)
  • Neural Networks and the Bias/Variance Dilemma — 1992, Neural Computation (library id: biasvariance1992)
  • Support-Vector Networks — 1995, Machine Learning (library id: svm1995)
  • Random Forests — 2001, Machine Learning (library id: randomforest2001)

31. Further reading

NVIDIA CUDA C Programming Guide; Dao et al. (2022) FlashAttention; Triton documentation.

Prefer primary sources and official documentation over blog summaries. When a source states a result without proof, mark it as a claim until you can derive it.

32. Practical exercises

  1. Implement vector addition in CUDA or Triton.
  2. Measure coalescing impact by striding input.
  3. Compare a tiled GEMM to cuBLAS.
  4. Complete the 11-step practical chain for Hierarchical clustering in My Tasks, starting with the from-scratch implementation.
  5. Record a plot and a numerical table, not just a sentence saying it worked.

33. Debugging challenges

  • Low bandwidth: inspect memory transactions.
  • Wrong results: check barriers and index math.
  • Launch failure: check grid dimensions.

For each bug, add a regression test that fails before the fix and passes after it.

34. Advanced exercises

  1. Implement FlashAttention-style online softmax.
  2. Overlap NCCL all-reduce with backward computation.
  3. Write a one-page critique of a paper that uses Hierarchical clustering: identify which assumptions it relies on and whether it checks them.

35. Interview questions

  • What is arithmetic intensity?
  • Why does warp divergence hurt?

Also be ready to: state the assumptions out loud before deriving anything; give a concrete counterexample where Hierarchical clustering fails; explain the difference between a theorem and an empirical observation about it; and describe how you would verify your implementation in a code review.

36. Research questions

  • Can learned tile policies beat autotuners?
  • What is the optimal precision for a given layer under error budget?

A research question is useful only if an experiment could answer it. For each one above, state what observation would falsify your preferred answer.

37. Mastery assessment

No mastery rubric is shown for this page. It is a generated template, and its rubric was boilerplate that did not match the topic. Use the core path or a hand-authored lesson for assessed material.

38. Implementation submission

No mastery rubric is shown for this page. It is a generated template, and its rubric was boilerplate that did not match the topic. Use the core path or a hand-authored lesson for assessed material.

39. Completion criteria

All of: derivation reproduced on paper; code executed with passing tests; numerical example matched; one failure mode reproduced and detected; assessment passed; primary source cited; results written up with hardware, seed and metric. Only then may the task be marked mastered.

Research papers linked to this concept