Module contents
Lesson 6 of 24Core 75 min

Advanced indexing, masks and scatter operations

Indexing with integer and Boolean arrays allows selection, rearrangement, and grouping without loops, with its own shape rules and always copying. Master gather and scatter (take_along_axis, np.add.at, bincount), indirect sorting (argsort, argpartition, searchsorted), and patterns that recur throughout the course: top-k, histograms, group aggregation, and embedding lookup.

After this lesson you can

  • Predict the result shape of indexing that combines basic and advanced indices across multiple axes.
  • Use Boolean masks and np.where to filter and select conditionally without loops.
  • Implement gather and scatter with take_along_axis and np.add.at and explain why a[idx] += 1 fails with repeated indices.
  • Solve top-k, ranking, and group aggregation with argsort, argpartition, unique, and bincount.
  • Translate these operations to their PyTorch equivalents (gather, scatter_add_, index_select, masked_fill, topk).

Before you start

Motivation: three problems that are one

Three apparently unrelated operations you will write dozens of times in this course:

  • Embedding lookup. Your GPT’s first layer receives a batch of token identifiers, ids of shape B×TB \times T, and returns a dd-dimensional vector per token. The “layer” is a table E∈RV×d\mat{E} \in \R^{V \times d} with one row per vocabulary word, and the whole operation is E[ids]: an array of shape B×T×dB \times T \times d built by reading rows of the table according to indices.
  • A language model’s top-k. To generate text with top-k sampling, keep the kk most probable tokens among V=50 000V = 50\,000. Sorting the entire vocabulary at each generation step wastes work: you only need to know which indices are highest, not sort the rest.
  • A column histogram. Counting how often each value appears, or summing an amount per customer, means writing to a counter array at positions dictated by the data, with many writes to the same position.

All three belong to the same family: arrays of indices specifying where to read (gather), where to write (scatter), or in what order to inspect data (indirect sorting). None needs a Python loop, and all have semantic traps that produce silently incorrect results: unexpected shapes, copies where views were expected, and lost increments.

[ ]Three problems, one familyBrowser
import numpy as np
rng = np.random.default_rng(0)

V, d = 1000, 8                               # vocabulario y dimensión
E = rng.standard_normal((V, d))              # tabla de embeddings
ids = np.array([[5, 17, 5], [999, 0, 17]])   # lote de 2 secuencias de 3 tokens
X = E[ids]                                   # lookup: gather de filas
print("lookup:", ids.shape, "->", X.shape)

logits = rng.standard_normal(V)
k = 5
top = np.argpartition(logits, -k)[-k:]       # los k mayores, sin ordenar
top = top[np.argsort(logits[top])[::-1]]     # ordenar solo esos k
print("top-5:", top, np.round(logits[top], 3))

edad = rng.integers(18, 80, size=10_000)
conteo = np.bincount(edad // 10)             # histograma por décadas: scatter de unos
print("décadas:", {10 * i: int(c) for i, c in enumerate(conteo) if c})

This lesson turns those three lines into something you master: you will predict the shape of any indexing expression, when NumPy copies, why a[idx] += 1 is wrong with repeated indices, why top-k takes linear time, and how everything translates to PyTorch. One convention before starting: since everything that follows is code, indices start at 0 in formulas too.

Indexing with integer arrays

In the ndarray lesson you saw basic indexing: integers and slices such as a[1, 2:5, ::2]. Each slice selects an arithmetic progression on its axis, so the result is described by an offset and new strides and is a view sharing memory with a. Advanced indexing breaks that structure: an index array can request positions in any order, including repeats, a[[3, 0, 3]], which is no longer an arithmetic progression. NumPy must construct a new array.

The first two rules make the mechanism powerful: index arrays combine element by element, not as a Cartesian product, like a zipper. a[[0, 2], [1, 3]] selects two elements, a[0, 1] and a[2, 3], not a 2×22 \times 2 block. For the block, broadcast indices yourself with orthogonal shapes, a[[[0], [2]], [1, 3]], or let np.ix_ do it.

Rule 3 is surprising. When advanced indices are separated by a slice, as in a[[0, 2], :, [1, 2]], there is no natural place for the axes of BB: where axis 0 was, or where axis 2 was? NumPy chooses not to choose and puts them first. Check it.

InteractiveIndex builder
a[[0, 2], :, [1, 2]]
a, shape (3, 4, 5) rows: axis 1 · columns: axis 2 a[0]a[1]a[2]01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859result 16111642475257
shape (2, 4) =2from B4axis 1
Hover over (or tap) a result cell.
Examples
Index for each axis
Advanced indicesaxis 0: (2,) · axis 2: (2,)
Broadcast shape BB(2,)
Placement of BBnon-adjacent: B moves to the front
Result shape(2, 4)
View or copy?copy
Advanced indices are not adjacent: NumPy puts the axes of BB at the front.
The array is a = np.arange(60).reshape(3, 4, 5): each cell shows its own flat index, so the value reveals its origin. Choose one index per axis and observe which cells are selected; each color is a position of the broadcast shape BB, and the small number indicates how often a cell is read. Hover over the result to see each value's origin. Explore the examples: the same index pair gives (2,4)(2, 4) or (3,2)(3, 2) depending on whether they are together or separated, and a simple 0 on axis 0 moves the new dimension.

What you should have seen:

  • BB determines the result shape, not the arrays separately. With [[0], [2]] (shape (2,1)(2, 1)) on axis 0 and [0, 1, 2] (shape (3,)(3,)) on axis 2, B=(2,3)B = (2, 3) and six “threads” of length 4 are selected, one per color.
  • Together or separated. a[:, [0, 2], [1, 2]] has shape (3,2)(3, 2): the advanced indices are contiguous and BB replaces axes 1 and 2 in place. a[[0, 2], :, [1, 2]] has shape (2,4)(2, 4): separated by :, BB goes first.
  • An integer can be an advanced index. a[0, :, [1, 2]] has shape (2,4)(2, 4) rather than (4,2)(4, 2), which is what a[0][:, [1, 2]] gives. With an array present, 0 counts as advanced and is separated from the other by :. This version of the rule causes the most errors in real code.
  • No arrays, no copy. a[1, 1:3, ::2] only uses basic indices: it is a view, even though it selects nonconsecutive cells.
  • Repeats are valid when reading. a[[2, 0, 2]] returns three blocks, two identical. When writing, as you will see, repeats are another story.
[ ]The shape rule, checkedBrowser
a = np.arange(60).reshape(3, 4, 5)
casos = {
    "a[[0, 2], :, [1, 2]]": a[[0, 2], :, [1, 2]],
    "a[:, [0, 2], [1, 2]]": a[:, [0, 2], [1, 2]],
    "a[0, :, [1, 2]]": a[0, :, [1, 2]],
    "a[[[0], [2]], :, [0, 1, 2]]": a[[[0], [2]], :, [0, 1, 2]],
    "a[np.ix_([0, 2], range(4), [1, 2])]": a[np.ix_([0, 2], range(4), [1, 2])],
    "a[1, 1:3, ::2]": a[1, 1:3, ::2],
}
for expr, r in casos.items():
    print(f"{expr:38s} forma {str(r.shape):11s} comparte memoria: {np.shares_memory(a, r)}")

# la regla 4, elemento a elemento: res[i, j] = a[I[i], j, J[i]] cuando B va delante
I, J = np.array([0, 2]), np.array([1, 2])
res = np.empty((2, 4), dtype=a.dtype)
for i in range(2):
    for j in range(4):
        res[i, j] = a[I[i], j, J[i]]
print("coincide con la definición:", np.array_equal(res, a[I, :, J]))

Composing indices and permutations

Indexing with an integer array composes functions. An array p of length mm with values in {0,…,n−1}\{0, \dots, n-1\} is a function p:{0,…,m−1}→{0,…,n−1}p: \{0, \dots, m-1\} \to \{0, \dots, n-1\}, and x[p] is the composition x∘px \circ p: position ii of the result reads position p(i)p(i) of x. This yields a useful rule to internalize.

Proof

By rule 4, x[p][q] at position ii equals x[p][q[i]] =x[p[q[i]]]= x[p[q[i]]], which is position ii of x[p[q]]: (x∘p)∘q=x∘(p∘q)(x \circ p) \circ q = x \circ (p \circ q). For the second part, q[p] = arange(n) says q∘p=id⁡q \circ p = \operatorname{id}. A permutation is bijective, so its left inverse is also its right inverse: p∘q=id⁡p \circ q = \operatorname{id}.

∎

The line q[p] = np.arange(n) is the idiomatic way to invert a permutation in linear time, and you will use it to calculate ranks later. Note: there q[p] appears to the left of an assignment, and that is not reading.

[ ]Composition, inverse, and assignmentBrowser
x = np.array([40, 10, 30, 20, 50])
p = np.argsort(x)                    # permutación que ordena
print("p =", p, " x[p] =", x[p])

q = np.empty_like(p)
q[p] = np.arange(len(p))             # inversa: q[p[i]] = i
print("q =", q, " p[q] =", p[q], " q es el rango de cada elemento")

i, j = np.array([4, 0, 2, 2]), np.array([3, 0, 1])
print("componer índices:", x[i][j], "==", x[i[j]])

b = x[[0, 1]]
b[0] = -1                            # modifica la copia, no x
x[[0, 1]] = -1                       # esto sí escribe en x (__setitem__)
print("x =", x)

The difference between the last two assignments is syntactic, which makes it deceptive. x[idx] on the right of = calls x.__getitem__(idx), returning a new copy. x[idx] = v is a different operation, x.__setitem__(idx, v), writing directly to x. In x[idx][0] = v, __getitem__ runs first (a copy), then __setitem__ on that copy, which is discarded.

Boolean masks

The second kind of advanced index is a Boolean array. It answers questions like “which elements satisfy this condition?” and is the vectorized form of if.

A mask being an integer index in disguise has two consequences. First: the result shape depends on data, because cc is unknown until the condition is evaluated. This makes masks awkward for compilers (JAX requires shapes known in advance) and explains why models prefer masking without selecting, replacing values rather than removing them. Second: in a 2D array, a[m] with m of shape (n0,n1)(n_0, n_1) flattens the result. To keep whole rows, the mask must be 1D on axis 0: X[y == 3] returns rows of class 3.

Three functions complete the toolbox:

  • np.nonzero(m) returns a tuple of coordinate arrays for True values (and np.flatnonzero, flat indices). np.argwhere(m) gives the same transposed, one row per element.
  • np.where(c, x, y), with three arguments, chooses elementwise between x and y according to c, broadcasting all three. It does not select: the result has the broadcast shape and loses no positions.
  • np.select(conds, valores, default) generalizes where to several regions: at each position it takes the value of the first true condition, or default if none.

The three most useful arithmetic operations on masks are trivial once you remember True equals 1: m.sum() counts, m.mean() gives the fraction, and m.any() / m.all() answer existence questions. Combine masks with &, |, and ~, never and, or, and not, which try to convert the entire array to one Boolean and fail.

[ ]Masks, where, and selectBrowser
x = np.array([-2.0, -0.5, 0.0, 0.5, 1.0, 2.5, np.nan])

m = x > 0
print("máscara:", m, " cuántos:", m.sum(), " fracción:", round(m.mean(), 3))
print("x[m] =", x[m], "  np.nonzero(m) =", np.nonzero(m)[0])
print("NaN > 0:", np.nan > 0, " NaN <= 0:", np.nan <= 0, " -> el NaN no está en ninguna de las dos")

# función por tramos: 0 si x < 0, x² si 0 <= x < 1, 2x − 1 si x >= 1
f_select = np.select([x < 0, x < 1], [0.0, x**2], default=2 * x - 1)
f_where = np.where(x < 0, 0.0, np.where(x < 1, x**2, 2 * x - 1))
print("select:", f_select)
print("where :", f_where)

# np.where no evita calcular la rama descartada: 1/x se evalúa en TODO x, también en x = 0
ramas = 1 / x
print("1/x en x = 0:", ramas[2], " (np.where lo descarta, pero se ha calculado)")
seguro = np.divide(1.0, x, out=np.zeros_like(x), where=(x != 0))
print("división solo donde x != 0:", seguro)

Two details in that output deserve attention. The final NaN satisfies neither x > 0 nor x <= 0: any comparison with NaN is false (except !=), so a mask and its “complement” written as another comparison do not cover the whole array. Both versions of the piecewise function return nan in the last position because np.select and np.where have no branch capturing it: conditions are false and default is evaluated on NaN. If NaN values are possible, handle them explicitly with np.isnan.

Gather and scatter: reading and writing by index

Advanced indexing has two uses so frequent that they have names in every framework.

In NumPy, 1D gather is x[idx] or np.take(x, idx); for table rows, E[ids] or np.take(E, ids, axis=0). Row-wise gather, where each row has its own indices, is np.take_along_axis(X, idx, axis=1), equivalent to indexing with two broadcast arrays: X[np.arange(n)[:, None], idx]. The canonical example is cross-entropy. With logits Z∈Rn×K\mat{Z} \in \R^{n \times K} and labels yiy_i, the loss needs the correct-class logit for each example, Zi,yiZ_{i, y_i}: one element per row, in different columns.

[ ]Row-wise gather: cross-entropy without loopsBrowser
logits = np.array([[2.1, 0.3, -1.0, 4.2, 0.0, 1.5],
                   [0.5, 3.3, 1.2, -0.4, 2.8, 0.1],
                   [-1.2, 0.8, 0.6, 1.9, -0.3, 5.0],
                   [1.4, 1.4, 2.2, 0.7, 3.6, -2.0]])
y = np.array([3, 1, 5, 2])                       # clase correcta de cada ejemplo
n = len(y)

pick1 = logits[np.arange(n), y]                  # dos arrays de índices difundidos: (n,) y (n,)
pick2 = np.take_along_axis(logits, y[:, None], axis=1)[:, 0]
print("logit correcto:", pick1, np.array_equal(pick1, pick2))

# entropía cruzada media con log-sum-exp estable: mean_i (logsumexp(z_i) − z_{i, y_i})
mx = logits.max(axis=1, keepdims=True)
lse = mx[:, 0] + np.log(np.exp(logits - mx).sum(axis=1))
print("entropía cruzada:", round(np.mean(lse - pick1), 6))

top2 = np.argsort(-logits, axis=1)[:, :2]         # top-2 de cada fila: índices por fila
print("top-2:", top2.tolist(), " valores:", np.take_along_axis(logits, top2, axis=1).tolist())
print("np.take, en cambio, cruza todas las filas con todos los índices:", np.take(logits, y, axis=1).shape)

The last line is the most common confusion. np.take(X, idx, axis=1) applies the same indices to every row, like X[:, idx], and has shape n×len(idx)n \times \text{len}(idx). take_along_axis and torch.gather use different indices in each row, so they require the index array to have as many axes as X: its shape is the output shape. This is the softmax cross-entropy you will implement later, and its gradient hides a surprise discovered in the next interactive.

InteractiveRow-wise gather and its gradient
x (4, 6)01230123452.10.3−1.04.20.01.50.53.31.2−0.42.80.1−1.20.80.61.9−0.35.01.41.42.20.73.6−2.0idx (4, 2)30145342out (4, 2)4.22.13.32.85.01.93.62.2
Hover over (or tap) an out cell.
Indices
Axis (dim)
Gradient
Ruleout[i, j] = x[i, idx[i, j]]
NumPynp.take_along_axis(x, idx, axis=1)
Using indicesx[np.arange(4)[:, None], idx]
PyTorchtorch.gather(x, 1, idx)
By contrast, np.take would giveshape (4, 4, 2)
Each cell of out reads x in its corresponding row and the column specified by idx: the index has the output shape, as in torch.gather. Click idx cells to change them and hover over out. Then enable backward: with g=∂L/∂outg = \partial L / \partial \text{out} equal to ones, the gradient with respect to x counts how many times each cell was read. Choose the repeated-indices example and see what happens in grad_x.

The backward pass you just saw is not a coincidence: gather and scatter-add are literally a matrix and its transpose.

The first part is a one-line calculation you do in the guided exercise. The second is the chain rule: the Jacobian of x↦Pιx\vb{x} \mapsto \mat{P}_\iota\vb{x} is Pι\mat{P}_\iota, and the gradient propagates by multiplying by its transpose.

ProofGather and scatter-add are adjoints
Prove: For all x∈Rn\vb{x} \in \R^n, y∈Rm\vb{y} \in \R^m and every index array ι\iota, ⟨gather⁡ιx,y⟩=⟨x,scatter⁡ιy⟩\inner{\operatorname{gather}_\iota \vb{x}}{\vb{y}} = \inner{\vb{x}}{\operatorname{scatter}_\iota \vb{y}}.
0
Recall that (gather⁡ιx)j=xιj(\operatorname{gather}_\iota \vb{x})_j = x_{\iota_j} and (scatter⁡ιy)i=∑j:ιj=iyj(\operatorname{scatter}_\iota \vb{y})_i = \sum_{j : \iota_j = i} y_j.

Step 1 of 3. Write the left-hand side as a sum.

Scatter: writing when indices collide

Repeated indices pose no problem when reading. When writing, they do. The natural expression for “add 1 at each position in idx” is a[idx] += 1, and with repeats it is incorrect. The reason lies in how Python translates the augmented operator:

a[idx] += v⟹tmp = a.__getitem__(idx);    tmp = tmp + v;    a.__setitem__(idx, tmp).\texttt{a[idx] += v} \quad\Longrightarrow\quad \texttt{tmp = a.\_\_getitem\_\_(idx)};\;\; \texttt{tmp = tmp + v};\;\; \texttt{a.\_\_setitem\_\_(idx, tmp)}.

The __getitem__ reads all positions at once before writing any. If position 4 appears three times in idx, tmp contains three copies of the old value, all three increment separately by 1, and __setitem__ writes the same number three times to the same cell. The result is one update per position, from the last write (NumPy does not even guarantee which is last). This is not a NumPy bug: the operation is correct, but it is not the one you wanted.

The correct operation is unbuffered: each contribution must read the current value, add, and write before the next arrives. NumPy offers it as the .at method of any ufunc (see ufuncs and reductions): np.add.at(a, idx, v), np.maximum.at(a, idx, v), np.multiply.at(...). For the most frequent case, adding into a zero-initialized 1D array, there is a specialized function: np.bincount(idx, weights=v, minlength=n), which counts (or sums weights) for each integer value of idx.

InteractiveScatter collisions
a[idx] += v read all, add, writeidxClick to change the index4Click to change the index1Click to change the index4Click to change the index0Click to change the index4Click to change the index1tmp111111a101102031405overwrites np.add.at(a, idx, v) each addition reads the current valueidx414041a102102033405+1
k = 5
Indices
Values to add
a[idx] += v[1, 1, 0, 0, 1, 0]
np.add.at in this order[1, 2, 0, 0, 3, 0]
np.bincount(idx, weights=v)[1, 2, 0, 0, 3, 0]
Overwritten writes3 of 6
With repeated indices, a[idx] += v applies one update per position (the last write). add.at and bincount accumulate all updates.
Above, a[idx] += v: first the whole tmp = a[idx] is read, then addition happens and finally values are written in order; each write to a repeated position overwrites the previous one, and crossed-out entries are lost contributions. Below, np.add.at: each contribution reads the current value. Press play and compare the two a rows. Then choose ‘float32’ and press ‘Another arrival order’ several times: with floating-point numbers, an accumulated sum depends on order, and a GPU guarantees none.

What you should have seen:

  • Lost contributions are exactly the repeats. Adding 1, a[idx] += 1 leaves a 1 at each touched position, losing len(idx) − len(np.unique(idx)) increments. With different values, one write per position “wins” (in practice, the last, shown by the interactive).
  • add.at and bincount always agree, and with integers contribution order does not matter: integer addition is associative and commutative.
  • For floating point, order matters. In float32, spacing between representable numbers near 10810^8 is 8, so 108+1=10810^8 + 1 = 10^8 (and also 108+3=10810^8 + 3 = 10^8). With example weights 10810^8, −108-10^8 and three ones, only ones arriving after the two large numbers survive: the result can be any value from 0 to 3, and only 3 is the exact sum.

The last point underlies a phenomenon encountered in GPU training. PyTorch’s scatter_add_ and index_add_ on CUDA use atomic additions: thousands of threads add simultaneously at the same memory location and hardware serializes them in an order depending on scheduling. Each run may add in a different order and yield a different result in the last bits. This is one source of GPU nondeterminism, measured in the PyTorch section.

[ ]a[idx] += 1 versus add.at and bincountBrowser
a = np.zeros(6)
idx = np.array([4, 1, 4, 0, 4, 1])
a[idx] += 1
print("a[idx] += 1      ->", a)
a = np.zeros(6)
np.add.at(a, idx, 1)
print("np.add.at        ->", a)
print("np.bincount      ->", np.bincount(idx, minlength=6))
w = np.array([1.0, 2, 3, 4, 5, 6])
print("con pesos        ->", np.bincount(idx, weights=w, minlength=6))
b = np.zeros(6)
b[idx] = w
print("b[idx] = w       ->", b, " (NumPy no garantiza qué escritura gana)")

# en 2D: sumar filas con repetición, el backward de una capa de embedding
G = np.zeros((4, 3))
np.add.at(G, [2, 0, 2], np.ones((3, 3)))
print(G)

bincount is more restrictive than add.at (1D only, nonnegative indices, new result in float64 or integer), and in return is faster: a single C loop without general ufunc machinery. Measure it against a Python loop over half a million contributions:

[ ]The cost of scatterBrowser
import time
rng = np.random.default_rng(1)
m, n = 500_000, 1000
idx = rng.integers(0, n, size=m)
w = rng.standard_normal(m)

def bucle(idx, w, n):
    out = [0.0] * n
    for i, v in zip(idx.tolist(), w.tolist()):
        out[i] += v
    return np.array(out)

def con_add_at(idx, w, n):
    out = np.zeros(n)
    np.add.at(out, idx, w)
    return out

def medir(f, *args, rep=3):
    best = float("inf")
    for _ in range(rep):
        t = time.perf_counter(); r = f(*args); best = min(best, time.perf_counter() - t)
    return r, best

r1, t1 = medir(bucle, idx, w, n)
r2, t2 = medir(con_add_at, idx, w, n)
r3, t3 = medir(lambda i, v, k: np.bincount(i, weights=v, minlength=k), idx, w, n)
for nombre, t in [("bucle de Python", t1), ("np.add.at", t2), ("np.bincount", t3)]:
    print(f"{nombre:16s} {t * 1e3:7.1f} ms   ({t1 / t:5.1f}x frente al bucle)")
print("iguales:", np.allclose(r1, r2), np.allclose(r1, r3))

The Python loop is tens of times slower than either vectorized version, and bincount beats add.at. For years np.add.at was notoriously slow; since NumPy 1.25 it has specialized indexed loops that speed it up by up to 60 times in simple cases (aligned operands and no type conversion), but bincount remains the choice for 1D summation.

Numerical verification of the adjoint theorem closes the section. The explicit selection matrix is useful for reasoning and testing, never for computation: it has m×nm \times n entries to store mm numbers.

[ ]Gather and scatter-add are a matrix and its transposeBrowser
rng = np.random.default_rng(2)
n, d, B, k = 7, 3, 5, 2
x = rng.standard_normal((n, d))
idx = rng.integers(0, n, size=(B, k))          # con repetidos, casi seguro
y = rng.standard_normal((B, k, d))

gx = x[idx]                                    # gather de filas: (B, k, d)
sy = np.zeros_like(x)
np.add.at(sy, idx, y)                          # scatter-add de filas: (n, d)
print("<G x, y> =", np.sum(gx * y))
print("<x, S y> =", np.sum(x * sy))

S = np.zeros((B * k, n))
S[np.arange(B * k), idx.ravel()] = 1           # matriz de selección P
print("P x es el gather:", np.allclose(S @ x, gx.reshape(-1, d)))
print("Pᵀ y es el scatter-add:", np.allclose(S.T @ y.reshape(-1, d), sy))

Indirect sorting

Sorting an array returns sorted values and forgets where each came from. Usually the opposite matters: which permutation sorts the data, so it can be applied to other arrays (sorting table rows by a column) or used to determine each element’s position.

When there are ties, several permutations sort x, and only one is stable. np.argsort defaults to kind="quicksort", actually introsort, fast and unstable; depending on platform and array size, it may appear stable, making the error more treacherous. With kind="stable" NumPy uses timsort or radix sort, which are stable (stability is studied in the algorithms module). This matters when tie order has meaning: sorting by a secondary key, breaking rank ties by arrival order, or reproducing an exact result.

[ ]Stable argsort, ranks, and multiple keysBrowser
v = np.array([3, 1, 3, 1, 2, 3, 1, 2])
print("estable:", np.argsort(v, kind="stable"))
print("        ", np.argsort(-v, kind="stable"), "(descendente estable: negar, no invertir)")
print("¡ojo!   ", np.argsort(v, kind="stable")[::-1], "(invertir rompe el orden de los empates)")

r = np.empty_like(v)
r[np.argsort(v, kind="stable")] = np.arange(len(v))
print("rangos:", r, " (los empates se desempatan por posición)")

# ordenar por dos claves: lexsort ordena por la ÚLTIMA clave y desempata con las anteriores
apellido = np.array(["ruiz", "gil", "ruiz", "gil", "paz"])
edad = np.array([40, 35, 22, 35, 51])
orden = np.lexsort((edad, apellido))           # por apellido y, a igualdad, por edad
print([f"{apellido[i]} {edad[i]}" for i in orden])

Linear-time top-k: argpartition

To keep the largest kk you do not need the order of the rest. np.argpartition(x, kth) returns a permutation pp with a much weaker guarantee than argsort: the element at position kth of x[p] is the one that would be there if everything were sorted, earlier elements are less than or equal and later ones greater than or equal, with no order among them. With kth = -k, the last kk indices of pp are the top-k. If you also want them sorted, sort only those kk: top[np.argsort(-x[top])], costing O(klog⁡k)\bigO(k \log k).

The algorithm behind it is quickselect (in the algorithms module). It uses the same partition as quicksort: choose a pivot, place larger values on one side and smaller on the other, and the pivot reaches its final position. Quicksort continues partitioning both sides. Quickselect checks where the pivot landed relative to boundary kk and continues only on the side containing it; the other is already decided.

InteractiveTop-k without sorting everything
  • pivot
  • larger than pivot / top-k
  • smaller than pivot
  • discarded or fixed
Sort all (quicksort)89 comparisons242322212019181716151413121110987654321kdone: everything sortedSelect (quickselect, like argpartition)44 comparisons242322212019181715161413121108254671193kdone: the 5 largest are left of k (unsorted)
sort
89
select
44
partition 16
Problem
24
5
Sort all: comparisons89 of 89 (expected 92.8)
Select top-k: comparisons44 of 44 (expected 52.5)
Partitions16 versus 5
With n=50 000n = 50\,000 and k=50k = 50958 728 versus 100 928 (×9.5)
Expected: 2(n+1)Hn−4n≈2nln⁡n2(n+1)H_n - 4n \approx 2n\ln n to sort and less than 3.39 n3.39\,n to select. With n=50 000n = 50\,000: 939 723 versus 100 730.
Both lanes start with the same data, and each range always uses the same random pivot, so quickselect's partitions are exactly the first ones in quicksort. After each partition, the pivot (orange) is in its final position, with larger values (green) to its left and smaller ones (blue) to its right. The initial state is the end: press play to see it step by step. Quicksort continues on both sides; quickselect discards the side without boundary kk (dashed line) and finishes when a pivot lands exactly there. Compare cumulative comparisons across the lanes. Change kk: sorting does not depend on kk, selection barely does. The last readout repeats the experiment with a language model's vocabulary.

What you should have seen: quickselect finishes in a handful of partitions, each on a range shrinking roughly geometrically, while quicksort needs on the order of nn partitions. With n=50 000n = 50\,000 and k=50k = 50, the expected value is about 9.4×1059.4 \times 10^5 comparisons for sorting and 1.0×1051.0 \times 10^5 for selection. The next theorem explains why selection is linear for any kk.

Proof

Partitioning a range of ss elements costs s−1<ss - 1 < s comparisons. Group execution into phases: phase j≥0j \ge 0 comprises steps where live range size ss satisfies (3/4)j+1n<s≤(3/4)jn(3/4)^{j+1} n < s \le (3/4)^j n. Each step of phase jj costs fewer than (3/4)jn(3/4)^j n comparisons.

Call a pivot central if it falls between the live range’s lower and upper quartiles. At least half the elements are central, so each pivot is central with probability at least 1/21/2, independently of what happened before. If central, each side has at most 3s/43s/4 elements, the live range shrinks to at most 3s/43s/4, and the current phase ends. The number of steps in a phase is therefore dominated by a geometric variable with parameter 1/21/2, whose mean is 2. Summing over phases,

E[comparaciones]<∑j≥02(34)jn=2n⋅11−3/4=8n.\E[\text{comparaciones}] < \sum_{j \ge 0} 2 \left(\tfrac{3}{4}\right)^j n = 2n \cdot \frac{1}{1 - 3/4} = 8n.∎

The bound is loose. For k=1k = 1 (the maximum), the exact value follows from a recurrence. If the pivot is the rr-th largest, with rr uniform in {1,…,n}\{1, \dots, n\}: for r=1r = 1 the algorithm stops, and for r>1r > 1 it continues with the r−1r - 1 elements larger than the pivot. Calling the expected number of comparisons C(n)C(n), with C(1)=0C(1) = 0, try to predict each step:

C(n)=(n−1)+1n∑m=1n−1C(m)C(n) = (n - 1) + \frac{1}{n}\sum_{m=1}^{n-1} C(m)
The first partition costs n−1n - 1; with probability 1/n1/n it continues on a range of size m=r−1m = r - 1, for each m=1,…,n−1m = 1, \dots, n-1 (and for r=1r = 1 it stops).
1/4

Solving the general recurrence gives the exact formula for any kk, used by the interactive as “expected”: C(n,k)=2[(n+1)Hn−(n+3−k)Hn+1−k−(k+2)Hk+n+3]C(n, k) = 2\big[(n+1)H_n - (n+3-k)H_{n+1-k} - (k+2)H_k + n + 3\big]. It ranges from 2n2n for extreme kk to about 2(1+ln⁡2) n≈3.39 n2(1 + \ln 2)\,n \approx 3.39\,n for the median. Quicksort, by contrast, makes an expected 2(n+1)Hn−4n≈2nln⁡n2(n+1)H_n - 4n \approx 2n\ln n comparisons, a factor ln⁡n\ln n more. NumPy uses introselect, not pure quickselect: quickselect with a median-of-medians fallback that activates upon detecting too many bad partitions and guarantees linear time even in the worst case.

[ ]argpartition, searchsorted, and inverse samplingBrowser
rng = np.random.default_rng(3)
x = rng.standard_normal(1_000)
k = 10
part = np.argpartition(x, -k)
print("¿los k últimos son los k mayores?", set(part[-k:]) == set(np.argsort(x)[-k:]))
print("frontera en su sitio:", x[part[-k]] == np.sort(x)[-k])
print("a la izquierda, todo <= frontera:", np.all(x[part[:-k]] <= x[part[-k]]))

# searchsorted: búsqueda binaria de la posición de inserción en un array ORDENADO
bordes = np.array([0, 18, 30, 45, 65])
edades = np.array([5, 18, 29, 30, 64, 65, 90])
print("tramo (side='right') :", np.searchsorted(bordes, edades, side="right") - 1)
print("np.digitize          :", np.digitize(edades, bordes) - 1)

# muestreo de una distribución discreta: buscar u ~ U(0, 1) en la función de distribución
p = np.array([0.5, 0.2, 0.2, 0.1])
cdf = np.cumsum(p)
u = rng.random(100_000)
muestras = np.searchsorted(cdf, u, side="right")
print("frecuencias:", np.bincount(muestras, minlength=4) / len(u))

The third tool in this section, np.searchsorted(a, v, side), performs vectorized binary search: for each value in v it returns the position where it should be inserted into sorted array a to keep it sorted, with side="left" before equals and side="right" after, in O(log⁡n)\bigO(\log n) per query. It assigns each datum to a bin (as np.digitize does), counts elements in an interval, searchsorted(a, hi, "right") - searchsorted(a, lo, "left"), and samples: if u∼Unif⁡(0,1)u \sim \Unif(0, 1), the position of uu in the cumulative distribution function is a sample from the distribution. This is inverse transform sampling, what NumPy’s rng.choice(n, p=p) does internally.

Lab: groupby from scratch

Group aggregation (summing each customer’s amounts, counting each user’s events, averaging by category) is central to tabular data analysis. pandas offers it as groupby, but underneath is a pattern you already have in full:

  1. Factorize keys. np.unique(claves, return_inverse=True) returns distinct sorted groups and, for each row, its group’s code, an integer in {0,…,G−1}\{0, \dots, G-1\}. This is essential because bincount needs small nonnegative indices, while real keys are arbitrary identifiers, strings, or huge integers.
  2. Scatter. bincount(cod) gives sizes; bincount(cod, weights=valores), sums; their quotient, means. There is no bincount for maximum, but there is np.maximum.at.
  3. Sorting alternative. If rows are sorted by key, each group is a contiguous segment, and np.add.reduceat(v, inicios) reduces each segment at once.
[ ]groupby with unique, bincount, and reduceatBrowser
rng = np.random.default_rng(4)
n = 150_000
clientes = rng.choice(10**9, size=5_000, replace=False)       # identificadores arbitrarios
cliente = clientes[rng.integers(0, len(clientes), size=n)]
importe = np.round(rng.gamma(2.0, 25.0, size=n), 2)

def groupby_bincount(claves, valores):
    grupos, cod = np.unique(claves, return_inverse=True)       # factorizar
    G = len(grupos)
    cuenta = np.bincount(cod, minlength=G)                      # scatter de unos
    suma = np.bincount(cod, weights=valores, minlength=G)       # scatter de valores
    maximo = np.full(G, -np.inf)
    np.maximum.at(maximo, cod, valores)                         # scatter con otra ufunc
    return grupos, cuenta, suma, suma / cuenta, maximo

def groupby_reduceat(claves, valores):
    orden = np.argsort(claves, kind="stable")
    k, v = claves[orden], valores[orden]
    inicio = np.flatnonzero(np.r_[True, k[1:] != k[:-1]])       # donde empieza cada grupo
    cuenta = np.diff(np.r_[inicio, len(k)])
    suma = np.add.reduceat(v, inicio)
    return k[inicio], cuenta, suma, suma / cuenta, np.maximum.reduceat(v, inicio)

g, cnt, s, mu, mx = groupby_bincount(cliente, importe)
print(f"{len(g)} grupos; el primero, {g[0]}: {cnt[0]} filas, suma {s[0]:.2f}, media {mu[0]:.2f}, máximo {mx[0]:.2f}")
print("las dos versiones coinciden:", all(np.allclose(a, b) for a, b in zip(groupby_bincount(cliente, importe), groupby_reduceat(cliente, importe))))

Now verify against pandas, the reference implementation (in the browser, the first pandas import takes a few seconds):

[ ]Verification against pandasBrowser
import pandas as pd

ref = pd.DataFrame({"c": cliente, "x": importe}).groupby("c")["x"].agg(["count", "sum", "mean", "max"])
for f in (groupby_bincount, groupby_reduceat):
    g, cnt, s, mu, mx = f(cliente, importe)
    ok = (np.array_equal(g, ref.index.to_numpy()) and np.array_equal(cnt, ref["count"].to_numpy())
          and np.allclose(s, ref["sum"]) and np.allclose(mu, ref["mean"]) and np.array_equal(mx, ref["max"].to_numpy()))
    print(f"{f.__name__:18s} coincide con pandas: {ok}")

Both versions are correct. Now timings, including the version someone without NumPy would write with a dictionary:

[ ]Timings: dictionary, NumPy, and pandasBrowser
def groupby_dict(claves, valores):
    acc = {}
    for c, v in zip(claves.tolist(), valores.tolist()):
        e = acc.get(c)
        if e is None:
            acc[c] = [1, v, v]
        else:
            e[0] += 1; e[1] += v
            if v > e[2]: e[2] = v
    return acc

_, cod = np.unique(cliente, return_inverse=True)
for nombre, f in [("diccionario", groupby_dict),
                  ("unique + bincount", groupby_bincount),
                  ("argsort + reduceat", groupby_reduceat),
                  ("solo bincount (con códigos)", lambda c, x: np.bincount(cod, weights=x)),
                  ("pandas", lambda c, x: pd.DataFrame({"c": c, "x": x}).groupby("c")["x"].agg(["count", "sum", "mean", "max"]))]:
    _, t = medir(f, cliente, importe, rep=2)
    print(f"{nombre:28s} {t * 1e3:7.1f} ms")

Interpreting timings has nuances. Both NumPy versions beat the dictionary, but pandas beats them, and the “bincount only” line explains why: scatter costs very little; factorization is expensive. np.unique factorizes by sorting in O(nlog⁡n)\bigO(n \log n), while pandas uses a hash table in expected O(n)\bigO(n). If keys are already small codes (vocabulary token IDs, a node index, an encoded category), you save that step and bincount is unbeatable. You will revisit this pattern and its variants in split-apply-combine.

Lab: embeddings, neighbors, and sparse gradients

The second lab brings the whole lesson together in a language model’s first layer. We build an embedding table with three “near-synonyms” of token 7 (their rows are row 7 plus a little noise), look up a batch, and find nearest neighbors by cosine similarity against the entire vocabulary, with row-wise top-k.

[ ]Lookup and neighbors by cosine similarityBrowser
rng = np.random.default_rng(5)
V, d = 5_000, 32
E = rng.standard_normal((V, d)).astype(np.float32)
E[[100, 200, 300]] = E[7] + 0.3 * rng.standard_normal((3, d)).astype(np.float32)   # tres casi sinónimos del 7

ids = np.array([[7, 42, 7, 999],
                [3, 7, 100, 0]])
X = E[ids]                                     # lookup: (B, T) -> (B, T, d)
print("lookup:", ids.shape, "->", X.shape, X.dtype)

def vecinos(E, consultas, k):
    En = E / np.linalg.norm(E, axis=1, keepdims=True)
    S = En[consultas] @ En.T                                   # coseno contra todo el vocabulario: (q, V)
    top = np.argpartition(-S, k - 1, axis=1)[:, :k]            # top-k por filas, sin ordenar
    s_top = np.take_along_axis(S, top, axis=1)
    orden = np.argsort(-s_top, axis=1, kind="stable")          # ordenar solo k por fila
    return np.take_along_axis(top, orden, axis=1), np.take_along_axis(s_top, orden, axis=1)

idx, sim = vecinos(E, np.array([7, 42]), k=5)
print("vecinos de 7: ", idx[0], np.round(sim[0], 3))
print("vecinos de 42:", idx[1], np.round(sim[1], 3))

Token 7 first finds itself (similarity 1), then its three synonyms with similarities between 0.930.93 and 0.950.95 (the typical value is 1/1+0.32≈0.961/\sqrt{1 + 0.3^2} \approx 0.96, with fluctuations of a few hundredths in dimension 32), then the closest “genuine” neighbor, around 0.60.6. That value is no accident: the cosine between independent Gaussian vectors of dimension d=32d = 32 has standard deviation about 1/d≈0.181/\sqrt{d} \approx 0.18, and the maximum of 5000 lies some three or four deviations above zero. This is what you see in an untrained embedding space.

Now the backward pass. If loss depends on the table only through X = E[ids], the adjoint theorem says ∂L/∂E\partial L / \partial \mat{E} is the scatter-add of ∂L/∂X\partial L / \partial \mat{X} onto rows ids. We check it against the dense formulation, where lookup is multiplication by a one-hot matrix O\mat{O} of shape BT×VBT \times V, X=OE\mat{X} = \mat{O}\mat{E}, and thus ∂L/∂E=O⊤ ∂L/∂X\partial L/\partial \mat{E} = \mat{O}\T\, \partial L/\partial \mat{X}:

[ ]The gradient of an embedding layerBrowser
dX = rng.standard_normal(X.shape).astype(np.float32)   # gradiente que llega de las capas superiores

dE = np.zeros_like(E)
np.add.at(dE, ids, dX)                                   # scatter-add de filas

O = np.zeros((ids.size, V), dtype=np.float32)            # one-hot de los ids: (B·T, V)
O[np.arange(ids.size), ids.ravel()] = 1
dE_densa = O.T @ dX.reshape(-1, d)
print("add.at == Oᵀ dX:", np.allclose(dE, dE_densa, atol=1e-5))
print("filas con gradiente:", np.flatnonzero(np.any(dE != 0, axis=1)), "de", V)

dE_mal = np.zeros_like(E)
dE_mal[ids] += dX                                        # el error clásico
err = np.abs(dE_mal - dE).max(axis=1)
print("error de dE[ids] += dX en las filas 7 y 42:", err[[7, 42]])

# actualización dispersa: solo se tocan las filas presentes en el lote
lr = 0.1
filas, cod = np.unique(ids, return_inverse=True)
G = np.zeros((len(filas), d), dtype=np.float32)
np.add.at(G, cod.ravel(), dX.reshape(-1, d))
E_nueva = E.copy()
E_nueva[filas] -= lr * G                                 # aquí sí vale: filas no tiene repetidos
print("actualización dispersa == densa:", np.allclose(E_nueva, E - lr * dE, atol=1e-6))

Three observations. The gradient is nonzero in only 6 rows out of 5000: it is sparse, which is why frameworks offer sparse embedding gradients (nn.Embedding(sparse=True) in PyTorch) and optimizers that update only touched rows. Token 7 occurs three times in the batch and dE[ids] += dX retains only one contribution: its row’s error is large, while row 42, appearing once, is correct. The final update uses advanced-index assignment, correct because np.unique guarantees filas has no repeats: the rule is “never with repeated indices” for a[idx] -=. This is what your GPT’s token embedding layer and embedding table lookup in general do.

The PyTorch version

All of the above exists in PyTorch under its own names. Translation is almost literal except for one point: PyTorch’s gather and scatter follow take_along_axis semantics (index shaped like the output, with the same number of axes as the input), rather than np.take.

NumPyPyTorchNote
x[idx], np.take(x, idx, axis)x[idx], torch.index_select(x, dim, idx)index_select requires 1D idx
np.take_along_axis(x, idx, axis)torch.gather(x, dim, idx)idx has the output shape
np.put_along_axis(x, idx, v, axis)x.scatter_(dim, idx, v)with repeats, the result is undefined
np.add.at(x, idx, v)x.index_add_(0, idx, v), x.scatter_add_(dim, idx, v)also x.index_put_((idx,), v, accumulate=True)
np.bincount(idx, weights, minlength)torch.bincount(idx, weights, minlength)
np.where(m, x, y), x[m] = vtorch.where(m, x, y), x.masked_fill(m, v)m broadcasts with x; shape does not change
np.argsort(x, kind="stable")torch.argsort(x, stable=True)
argpartition + take_along_axistorch.topk(x, k, dim)returns sorted values and indices
np.searchsorted(a, v, side)torch.searchsorted(a, v, right=...)

And the same error under another name: in PyTorch, x[idx] += 1 also translates to index_put_ without accumulation and loses repeats. The next cell checks the table and measures scatter_add_ nondeterminism on the lab GPU; it needs PyTorch, so it runs locally.

[ ]Equivalences and GPU nondeterminismLocal GPU
import numpy as np
import torch

rng = np.random.default_rng(0)
x_np = rng.standard_normal((4, 6)).astype(np.float32)
idx_np = np.argsort(-x_np, axis=1)[:, :2]
x, idx = torch.from_numpy(x_np), torch.from_numpy(idx_np)

ids = torch.tensor([4, 1, 4, 0, 4, 1])
a = torch.zeros(6)
a[ids] += 1                                                  # el mismo error que en NumPy
comprobaciones = {
    "gather == take_along_axis": np.allclose(torch.gather(x, 1, idx).numpy(), np.take_along_axis(x_np, idx_np, axis=1)),
    "topk == argsort[:k]": torch.equal(torch.topk(x, 2, dim=1).indices, idx),
    "index_select == take": np.allclose(torch.index_select(x, 1, torch.tensor([0, 5])).numpy(), np.take(x_np, [0, 5], axis=1)),
    "masked_fill == where": np.allclose(x.masked_fill(x < 0, 0).numpy(), np.where(x_np < 0, 0, x_np)),
    "scatter_add_ == add.at": torch.equal(torch.zeros(6).scatter_add_(0, ids, torch.ones(6)), torch.tensor([1., 2, 0, 0, 3, 0])),
    "index_add_ == add.at": torch.equal(torch.zeros(6).index_add_(0, ids, torch.ones(6)), torch.tensor([1., 2, 0, 0, 3, 0])),
    "x[ids] += 1 pierde repetidos": torch.equal(a, torch.tensor([1., 1, 0, 0, 1, 0])),
}
for nombre, ok in comprobaciones.items():
    print(f"{nombre:30s} {ok}")

if torch.cuda.is_available():
    g = torch.Generator(device="cuda").manual_seed(0)
    dst = torch.randint(0, 10, (1_000_000,), device="cuda", generator=g)
    w = torch.randn(1_000_000, device="cuda", generator=g)
    def cinco():
        return [torch.zeros(10, device="cuda").scatter_add_(0, dst, w) for _ in range(5)]
    r = cinco()
    print("\nscatter_add_ en CUDA, ¿idénticas bit a bit?", [torch.equal(r[0], ri) for ri in r])
    print("diferencia máxima entre ejecuciones:", max((r[0] - ri).abs().max().item() for ri in r))
    torch.use_deterministic_algorithms(True)
    r = cinco()
    print("con use_deterministic_algorithms(True):", [torch.equal(r[0], ri) for ri in r])
    torch.use_deterministic_algorithms(False)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With a million contributions across ten positions, atomic additions almost always yield results differing in the third or fourth decimal place across runs (each position sums about 10510^5 numbers, with value on the order of 10210^2 and relative error on the order of 10−510^{-5}). With torch.use_deterministic_algorithms(True), PyTorch switches to a slower deterministic implementation. Not all operations have one: torch.bincount with weights on CUDA, for example, raises an error in deterministic mode. When that cost is worthwhile is addressed in GPU nondeterminism.

Common mistakes

Exercises

QuizShape of mixed indexing
Let a be an array of shape (5,6,7)(5, 6, 7). What is the shape of a[[0, 1], :, [2, 3]]?
QuizFive shapes
Let a be an array of shape (8,9,10,11)(8, 9, 10, 11). Which statements are correct?

More than one answer may be correct.

NumericAn increment with collisions
After a = np.zeros(5) and a[[1, 1, 3, 1]] += 1, what is a[1]?
QuizWhat writes to the original array?
Starting each time from a = np.arange(10.0), which instructions modify a?

More than one answer may be correct.

QuizA three-piece function
You want to evaluate, for an array x of floats without NaN, the function f(x)=0f(x) = 0 if x<0x < 0, f(x)=x2f(x) = x^2 if 0≤x<10 \le x < 1 and f(x)=2x−1f(x) = 2x - 1 if x≥1x \ge 1. Which implementations are correct?

More than one answer may be correct.

NumericThe rank of a tie
Let x = np.array([30, 10, 20, 10, 50]). Compute r = np.empty(5, dtype=int) and r[np.argsort(x, kind='stable')] = np.arange(5). What is r[3]?
NumericSumming by group
With claves = np.array([7, 3, 7, 9, 3, 7]) and valores = np.array([1., 2., 3., 4., 5., 6.]), run g, cod = np.unique(claves, return_inverse=True). What is np.bincount(cod, weights=valores)[1]?
NumericThe savings from selection
With a random pivot, how many expected comparisons does quickselect save finding the maximum (k=1k = 1) versus quicksort sorting, for n=10n = 10? Use 2(n+1)Hn−4n2(n+1)H_n - 4n for quicksort.
Quiztorch.gather
Let x = torch.arange(15.).reshape(3, 5) and idx = torch.tensor([[4], [0], [2]]). What does torch.gather(x, 1, idx) return?
Codetopk with argpartition
Implement topk(x, k, axis=-1) returning (valores, indices) with the k largest elements of x along axis, in descending order, so np.take_along_axis(x, indices, axis) reproduces valores. Use np.argpartition to avoid sorting the entire axis and np.take_along_axis to gather. Tests compare with a full sort, include ties (any tied index is valid, without repeats), and the case k equals the axis size.
import numpy as np

def topk(x, k, axis=-1):
  # 1) argpartition para separar los k mayores
  # 2) take_along_axis para leer sus valores
  # 3) ordenar SOLO esos k, de mayor a menor
  pass
Shift+Enter to run
Codeone-hot, its inverse, and a weighted histogram
Implement without loops: one_hot(y, K), which for an integer array y in [0,K)[0, K) of any shape returns a float array of shape y.shape + (K,) with 1 at each label's position; from_one_hot(Y), its inverse (the position of 1 on the last axis); and weighted_hist(x, edges, w), which must match np.histogram(x, bins=edges, weights=w)[0]: intervals [ei,ei+1)[e_i, e_{i+1}) except the last, which is closed, and values outside [e0,euˊltimo][e_0, e_{\text{último}}] are ignored. Use np.searchsorted and np.bincount.
import numpy as np

def one_hot(y, K):
  pass

def from_one_hot(Y):
  pass

def weighted_hist(x, edges, w):
  pass
Shift+Enter to run

Summary

Key idea
An index array is a function of positions: reading with it is gather, accumulating writes is scatter-add (its transpose and therefore its gradient), and indirect sorting computes the permutation to apply. Gather and scatter are linear in data size; sorting costs O(nlog⁡n)\bigO(n \log n), but top-k selection is linear again. Each has a semantic trap: the shape of BB and copying on reads, collisions on writes, ties in sorting.
  • Advanced indexing. Integer arrays (and integers, if any array is present) broadcast together to shape BB and combine elementwise. If contiguous, BB takes their place; otherwise it goes first. The result is always a copy; a[idx] = v writes to a, a[idx][0] = v does not. For the Cartesian product, use np.ix_.
  • Masks. a[m] equals a[np.nonzero(m)] and its shape depends on data. np.where(c, x, y) and np.select choose without changing shape, but evaluate every branch. Comparisons with NaN are false.
  • Gather and scatter. take_along_axis and torch.gather read with an index shaped like the output; np.take and index_select use the same indices for every row. With repeated indices, a[idx] += v loses contributions; np.add.at, bincount, index_add_, and scatter_add_ accumulate. On GPU the accumulation order is not fixed and floating-point results may vary.
  • Indirect sorting. argsort gives the sorting permutation; its inverse, r[p] = arange(n), gives ranks; use kind="stable" when ties matter. argpartition solves top-k in expected linear time (quickselect makes fewer than 8n8n comparisons, in practice between 2n2n and 3.4n3.4n) and searchsorted searches a sorted array in logarithmic time.
  • Patterns. groupby is factorization (unique with return_inverse) and scatter (bincount, ufunc.at, reduceat); embedding lookup is row gather and its backward pass sparse scatter-add.